AngularJS:从指令调用外部函数? [英] AngularJS: Call external functions from directive?
问题描述
我正在尝试创建一个使用控制器中定义的外部功能的自定义组件,但是遇到了不同的问题.
I'm trying to create a custom component that uses external functions defined in the controller, but I'm experiencing different problems.
示例:
我想使用控制器中定义的外部函数创建自定义输入,例如:
I want to create a custom input with a external function defined in the controller, like:
<custom-input type="text" ext-function="checkLength(this)"></custom-input>
<custom-input type="password" ext-function="checkPasswordIsStrong(this)"></custom-input>
问题是我尝试了不同的方法来从指令中调用此方法,但没有成功,例如:
The thing is that I've tried different approaches to call this from the directive but with no success at all, like:
指令:
Directive:
link: function(scope, element, attrs, ctrl) {
if (typeof(attrs.extFunction) != "undefined") {
scope.$eval(attrs.extFunction);
}
}
控制器
Controller
$scope.checkLength = function(element){
console.log('Checking length from: '+element);
}
$scope.checkPasswordIsStrong = function(element){
console.log('Checking password from: '+element);
}
- 如何从指令内部调用这些动态外部函数?
- 如何将元素从html传递给函数?我使用了"this",但它根本不起作用.
已编辑
我终于明白了.
解决方案: http://plnkr.co/edit/6A9DsCruV7yTQmTRU65j?p=preview
推荐答案
例如,您可以使用&
绑定,例如:
For example, you can use the &
binding, like:
scope: {
'fctn': '&extFunction'
},
这样,它便成为了指令范围的一部分.请参阅: http://docs.angularjs.org/guide/directive
That way it is part of the directive's scope. See: http://docs.angularjs.org/guide/directive
这篇关于AngularJS:从指令调用外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!