javascript - Angular Directive(指令)可以将参数传递给指令属性中指定的表达式中的函数吗?

标签 javascript angularjs angularjs-directive angularjs-scope

我有一个表单指令,它使用指定的 callback 属性和一个隔离范围:

scope: { callback: '&' }

它位于 ng-repeat 内,因此我传入的表达式包含对象的 id 作为回调函数的参数:

<directive ng-repeat = "item in stuff" callback = "callback(item.id)"/>

当我完成指令后,它会从其 Controller 函数调用 $scope.callback()。在大多数情况下,这很好,这就是我想做的所有事情,但有时我想从 directive 本身内部添加另一个参数。

是否有一个 Angular 表达式允许这样做:$scope.callback(arg2),导致 callback 被调用 arguments = [item.id , arg2]?

如果没有,最简洁的方法是什么?

我发现这是可行的:

<directive 
  ng-repeat = "item in stuff" 
  callback = "callback" 
  callback-arg="item.id"/>

scope { callback: '=', callbackArg: '=' }

和调用的指令

$scope.callback.apply(null, [$scope.callbackArg].concat([arg2, arg3]) );

但我不认为它特别整洁,它涉及在隔离范围内放置额外的东西。

有没有更好的办法?

Plunker playground here (打开控制台)。

最佳答案

如果你像@lex82 提到的那样声明你的回调

callback = "callback(item.id, arg2)"

您可以使用对象映射在指令范围内调用回调方法,它会正确地进行绑定(bind)。喜欢

scope.callback({arg2:"some value"});

不需要$parse。查看我的 fiddle (控制台日志)http://jsfiddle.net/k7czc/2/

更新:documentation 中有一个小例子。 :

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

关于javascript - Angular Directive(指令)可以将参数传递给指令属性中指定的表达式中的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19889615/

相关文章:

javascript - 如何绘制形状然后将其声明为变量?

javascript - 当同一引用上有多个监听器时,从 Firebase 中删除监听器

javascript - AngularJS 服务不返回 promise

javascript - 如何在没有 typescript 的情况下在 Angular 2 中注入(inject) Http

angularjs - 如何将 ng-href 与绝对 url 一起使用?

javascript - 解析用箭头分隔的数字

javascript - 脚本中的 jQuery attr 和 prop 组合

javascript - 为什么我的工厂出现喷油器错误?

javascript - Angular.js 和服务器端搜索 - 如何,最佳实践

javascript - $translateProvider.useStaticFilesLoader 的 Angular Translate 异步计时问题