gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:17:13 28 4
gpt4 key购买 nike

我有一个表单指令,它使用指定的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com