AngularJS:从指令调用外部函数? [英] AngularJS: Call external functions from directive?

查看:30
本文介绍了AngularJS:从指令调用外部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

指令:

 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 传递给函数?我使用了这个",但它根本不起作用.

已编辑

我终于明白了.

解决方案: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆