我想使用父列表(Foo)的索引作为子列表(foos.bars)中函数调用的参数。
我找到一篇文章,有人推荐使用$parent.$index,但$index不是$parent的属性。
如何访问父ng-repeat的索引
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>发布于 2013-02-12 06:51:10
我的示例代码是正确的,问题出在我实际代码中的其他方面。尽管如此,我知道很难找到这样的例子,所以我回答了这个问题,以防其他人在看。
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>发布于 2013-09-20 18:52:17
根据ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat,您可以将键或数组索引存储在您选择的变量中。(indexVar, valueVar) in values
这样你就可以写
<div ng-repeat="(fIndex, f) in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething(fIndex)">Add Something</a>
</div>
</div>
</div>上一级的$parent.$index仍然是相当干净的,但几个家长上一级,事情可能会变得混乱。
注意:每个作用域都将继续定义$index,它不会被fIndex所取代。
发布于 2014-01-04 04:48:39
看看my answer to a similar question吧。
通过给$index添加别名,我们不必编写像$parent.$parent.$index这样疯狂的东西。
当$parent.$index使用ng-init时,解决方案更加优雅
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>Plunker:http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p=info
https://stackoverflow.com/questions/14807258
复制相似问题