从内部ng repeat访问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$索引,因此可以使用$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

最新更新