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

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

问题描述

我要创建一个链接到一个属性的指令。该属性指定应在范围被调用的函数。但我也想一个参数传递给该链接函数内部确定的函数。

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>

在我绑定到一个jQuery事件,它传递的参数我需要传递给函数的链接功能:

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); };
}

不传递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

推荐答案

马尔科的解决方案行之有效

要与推荐的方式角(如由treeface的plunkr)对比度使用回调前pression不需要定义前pressionHandler。在马尔科的例子变化:

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:

在模板

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

在指令链接功能

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

这确实有一个缺点相比,马尔科的解决方案 - 第一次加载theMethodToBeCalled功能将与myParam调用===未定义

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

一个工作exampe可以在 @treeface Plunker

A working exampe can be found at @treeface Plunker

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

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