angularjs 指令调用属性中指定的函数并将参数传递给它 [英] angularjs directive call function specified in attribute and pass an argument to it

查看:27
本文介绍了angularjs 指令调用属性中指定的函数并将参数传递给它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个链接到属性的指令.该属性指定应在作用域上调用的函数.但我也想将参数传递给链接函数内部确定的函数.

</div>

在链接函数中,我绑定了一个 jQuery 事件,该事件传递了一个我需要传递给函数的参数:

app.directive("myMethod",function($parse) {限制:'A',链接:功能(范围,元素,属性){var expressionHandler = $parse(attrs.myMethod);$(element).on('theEvent',function( e, rowid ) {id =//调用某个函数来根据 rowid 确定 idscope.$apply(function() {expressionHandler(id);});}}}app.controller("myController",function($scope) {$scope.theMethodToBeCalled = function(id) { alert(id);};}

不传递 id 我可以让它工作,但是一旦我尝试传递一个参数,该函数就不再被调用

解决方案

Marko 的解决方案运行良好.

与推荐的 Angular 方式(如 treeface 的 plunkr 所示)形成对比的是使用不需要定义 expressionHandler 的回调表达式.在 marko 的示例更改中:

在模板中

<div my-method="theMethodToBeCalled(myParam)"></div>

在指令链接函数中

$(element).click(function(e, rowid) {scope.method({myParam: id});});

与 marko 的解决方案相比,这确实有一个缺点 - 在第一次加载时,MethodToBeCalled 函数将在 myParam === undefined 的情况下被调用.

可以在 @treeface Plunker

找到工作示例

I want to create a directive that links to an attribute. The attribute specifies the function that should be called on the scope. But I also want to pass an argument to the function that is determined inside the link function.

<div my-method='theMethodToBeCalled'></div>

In the link function I bind to a jQuery event, which passes an argument I need to pass to the function:

app.directive("myMethod",function($parse) {
  restrict:'A',
  link:function(scope,element,attrs) {
     var expressionHandler = $parse(attrs.myMethod);
     $(element).on('theEvent',function( e, rowid ) {
        id = // some function called to determine id based on rowid
        scope.$apply(function() {expressionHandler(id);});
     }
  }
}

app.controller("myController",function($scope) {
   $scope.theMethodToBeCalled = function(id) { alert(id); };
}

Without passing the id I can get it working, but as soon as I try to pass an argument, the function is not called anymore

解决方案

Marko's solution works well.

To contrast with recommended Angular way (as shown by treeface's plunkr) is to use a callback expression which does not require defining the expressionHandler. In marko's example change:

In template

<div my-method="theMethodToBeCalled(myParam)"></div>

In directive link function

$(element).click(function( e, rowid ) {
  scope.method({myParam: id});
});

This does have one disadvantage compared to marko's solution - on first load theMethodToBeCalled function will be invoked with myParam === undefined.

A working exampe can be found at @treeface Plunker

这篇关于angularjs 指令调用属性中指定的函数并将参数传递给它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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