我想使用父列表(foos)的索引作为子列表(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>
看看我对类似问题的回答。
通过别名$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>
砰砰作响:http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p=info
根据ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat,您可以将键或数组索引存储在您选择的变量中。(indexVar, valueVar)
所以你可以写
<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取代。