【问题标题】:access ng-repeat $index from a inner ng-repeat从内部 ng-repeat 访问 ng-repeat $index
【发布时间】:2015-11-11 18:59:18
【问题描述】:
知道 ng-repeat 创建了一个作用域,我如何从子 ng-repeat 访问父 ng-repeat 的 $index?
标记
<div ng-repeat="first in arr">
here there is the first level $index
<div ng-repeat="second in first.arr">
in here I need access to the first level $index
</div>
</div>
【问题讨论】:
标签:
angularjs
data-binding
foreach
angularjs-ng-repeat
ng-repeat
【解决方案1】:
每当ng-repeat 迭代创建一个 DOM 时,它也会创建一个 DOM,其原型继承自当前运行的范围。
由于您想访问内部ng-repeat 中的外部ng-repeat 的ng-repeat $index,您可以使用$parent.$index 指示父级ng-repeat
<div ng-repeat="first in arr">
here there is the first level $index
<div ng-repeat="second in first.arr">
in here I need access to the first level {{$parent.$index}}
</div>
</div>
虽然解决此问题的更简洁的解决方案是,在外部 ng-repeat 上使用 ng-init 并在范围变量中使用外部 index,通过它您可以摆脱 $parent 关键字。
<div ng-repeat="first in arr" ng-init="parentIndex=$index">
here there is the first level $index
<div ng-repeat="second in first.arr">
in here I need access to the first level {{parentIndex}}
</div>
</div>
【解决方案2】:
<div ng-repeat="first in [1,2,3]">
here there is the first level {{$index}}
<div ng-repeat="second in ['a', 'b', 'c']">
in here I need access to the first level {{$parent.$index}} / {{$index}}
</div>
输出:
here there is the first level 0
in here I need access to the first level 0 / 0
in here I need access to the first level 0 / 1
in here I need access to the first level 0 / 2
here there is the first level 1
in here I need access to the first level 1 / 0
in here I need access to the first level 1 / 1
in here I need access to the first level 1 / 2
here there is the first level 2
in here I need access to the first level 2 / 0
in here I need access to the first level 2 / 1
in here I need access to the first level 2 / 2