Search code examples
javascripthtmlangularjsangular-directive

How to call a controller function inside AngularJS directive


Controller in page :

(function () {
 'use strict';
  angular.module('LVS').controller('LVSCtrl', LVSCtrl);
  function LVSCtrl($scope) {
   $scope.OnChange = function() {
   // do
   }
  }
 })();

This is my directive code My Directive code :

(function () {
  'use strict';

  angular.module('LVS')
      .directive('taEmp', taEmp);

  function taEmp() {
      return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            ngDisabled: '=',
            ngReadonly: '=',
            ngChange: '&',
        },
        templateUrl: 'app/pages/ESS-TA/Common/Directives/TAEmpPicker.html',

    }

    })();

My Directive in page :

<ta-emp ng-model="empCode" ng-change="OnChange()"></ta-emp>

My directive not call function in controller


Solution

  • I made it work by using $watch inside your directive and parsing an controller function as param into it. The function gonna be executed once the input value has changed.

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope) {
        $scope.name = '';
        $scope.someFunction = function (data) {
           console.log(data);
        };
    });
    
    myApp.directive('myDirective', function () {
    
      return {
          restrict: 'E',
          scope: {
            model: '=ngModel',
            function: '='
          },
          template: '<input type="text" ng-model="model" function="function" my-directive>',
          link: function (scope, element, attrs) {
             scope.$watch('model', function (newValue, oldValue) {
               if (newValue && newValue !== oldValue) {
                 if (typeof scope.function === 'function') {
                   scope.function('test');
                 }
               }
             }, true);
          }
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl">
      <my-directive ng-model="name" function="someFunction"></my-directive>
    </div>