如何将函数传递给 ng-repeat 中的 angular 指令(arg 未定义)?

How do I pass a function to an angular directive inside ng-repeat (arg is undefined)?

父指令:

<autosuggest
    click-match="addTag(tag)">
</autosuggest>

addTag函数定义在父控制器中。它被调用,但参数未定义。

这是 <autosuggest> 实现:

scope: {
    clickMatch: '&'
}

在视图中:

<li ng-repeat="match in matches">
    <span ng-click="clickMatch(match)">{{match.name}}</span>
</li>

clickMatch 函数正在调用父函数的 addTag(tag) 函数,但参数 tag 未定义。

通过 & 传递到指令中的函数以修改后的形式出现在隔离作用域中。他们取一个对象的键值对

variableNameInExternalTemplate: expressionInIsolatedScope

在您的例子中,键是 tag,值是 match,因此您的 ng-click 属性应该类似于

<span ng-click="clickMatch({tag: match})"></span>

如果您还想通过点击传递 $event,您可以对 $event 变量执行相同的操作

<span ng-click="clickMatch({tag: match, $event: $event})"></span>

确保将 $event 添加到使用指令的模板中的参数列表中

<autosuggest click-match="addTag(tag, $event)"></autosuggest>