如何在 AngularJS 指令中调用控制器函数

How to call a controller function inside AngularJS directive

页面控制器:

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

这是我的指令代码 我的指令代码:

(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',

    }

    })();

我在页面中的指令:

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

我的指令没有调用控制器中的函数

我通过在你的指令中使用 $watch 并将控制器函数作为参数解析到其中来使其工作。一旦输入值改变,该函数就会被执行。

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>