从内部 ng-repeat 访问 ng-repeat $index

access ng-repeat $index from a inner ng-repeat

知道 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>

每当 ng-repeat 迭代创建一个 DOM 时,它也会创建一个 DOM,其新作用域原型继承自当前 运行 作用域。

因为你想在内部 ng-repeat 中访问外部 ng-repeatng-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>
<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