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

时间:2015-11-11 18:59:18

标签: angularjs data-binding foreach angularjs-ng-repeat ng-repeat

知道ng-repeat会创建范围,如何从孩子$index访问父级ng-repeat的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 $index
   </div>
</div>

2 个答案:

答案 0 :(得分:3)

每当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-init上使用ng-repeat并在范围变量中使用外index,您可以通过该变量摆脱{{1} } keyword。

$parent

答案 1 :(得分:0)

<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