AngularJS:从指令调用外部函数?

时间:2014-01-06 06:11:32

标签: angularjs angularjs-directive

我正在尝试创建一个使用控制器中定义的外部函数的自定义组件,但我遇到了不同的问题。

示例:

我想使用控制器中定义的外部函数创建自定义输入,例如:

<custom-input type="text" ext-function="checkLength(this)"></custom-input>
<custom-input type="password" ext-function="checkPasswordIsStrong(this)"></custom-input>

问题在于我尝试了不同的方法来从指令中调用它,但根本没有成功,例如:

指令:

 link: function(scope, element, attrs, ctrl) {
    if (typeof(attrs.extFunction) != "undefined") {
       scope.$eval(attrs.extFunction);
    }
 }

控制器

$scope.checkLength = function(element){
   console.log('Checking length from: '+element);
}

$scope.checkPasswordIsStrong = function(element){
   console.log('Checking password from: '+element);
}
  1. 如何从指令内部调用这些动态外部函数?
  2. 我怎样才能将元素从html传递给函数?我使用了“this”,但它根本不起作用。
  3. EDITED

    我终于明白了。

    解决方案:http://plnkr.co/edit/6A9DsCruV7yTQmTRU65j?p=preview

1 个答案:

答案 0 :(得分:3)

例如,您可以使用&绑定,例如:

scope: {
    'fctn': '&extFunction'
},

这样它就是指令范围的一部分。请参阅:http://docs.angularjs.org/guide/directive

相关问题