AngularJs:从指令属性调用函数

时间:2013-11-21 15:01:06

标签: angularjs angularjs-directive

这看起来很简单,我在某种程度上有效,但我的解决方案存在一些问题。

场景是我想将一个函数(toggleValue())传递给一个指令,然后通过指令模板中的ngChange调用该函数。基本设置是:

// html
<div class="my-directive" ng-model="my_model" ng-change="toggleValue()"></div>

// angular directive
myApp.directive('myDirective', function() {
  return {
      scope: {
        restrict: 'C',
        model: '=ngModel',
        action: '=ngChange'
      },
      template: '<input type="checkbox" ng-model="model" ng-change="action">'
  }
}

这有点过于简单,因为它已经脱离了上下文,但它展示了我正在尝试做的事情。这也有效。它的问题在于它被多次调用 - 甚至在它被明确调用之前。这似乎是由于对动作的双向绑定。据我了解,&amp;应该用于隔离方法但是当我将操作更改为'&ngChange'函数时,toggleValue()永远不会被调用。

我尝试将解决方案纳入Call a controller function from a directive without isolated scope in AngularJS,但没有取得任何成功。使用$apply()给了我$ digest错误,使用$eval()没有回应。

link: function (scope, element, attrs) {
  scope.$eval(attrs.action);
}

1 个答案:

答案 0 :(得分:4)

要传递函数,您需要在范围定义中使用&而不是=

action: '&ngChange'

然后你需要在指令模板中调用动作:

ng-change="action()"
相关问题