【发布时间】:2015-05-19 19:01:16
【问题描述】:
我是 Angular JS 的新手,我正在尝试使用 ng-repeat 在我的表中生成多行,并且在每一行中应该有一个按钮来触发具有不同参数的函数
<div ng-controller="testing">
<table>
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
<th>button</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{ item.prop1 }}</td>
<td>{{ item.prop2 }}</td>
<td><button ng-click="myFunction(item.id)">Trigger Function</button></td>
</tr>
</tody>
</table>
</div>
这当然行不通,因为 ng-repeat 创建了自己的范围,而 myFunction 是在父范围(即测试控制器)中定义的。
但是,我只能在 Google 结果中找到无法正常工作的原因,但缺乏解决问题的方法。我应该如何更正我的代码以便 ng-click 起作用?有没有办法在 ng-repeat 范围内定义 myFunction 或者有没有办法告诉我想要父范围内的函数?
【问题讨论】:
-
应该可以,试试
ng-click="$parent.myFunction(item.id)" -
它会在其他地方出现一些问题。这是 plunker plnkr.co/edit/yrxmcndiNIwBZd4YDixH
-
这不应该是父子范围的问题。
-
你是对的。问题在别处。我得到了子控制器,而您看到的模拟代码在父控制器中时,该功能被错误地放入了子控制器中。愚蠢的错误。
标签: javascript angularjs angularjs-scope angularjs-ng-repeat