andresmijares25 andresmijares25 - 5 months ago 76
AngularJS Question

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

Knowing that ng-repeat create a scope, how do I access the

$index
of a parent ng-repeat from a child
ng-repeat
?

Markup

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

Answer

Whenever ng-repeat iterate to create a DOM, it also does create a DOM, with new scope which prototypically inherited from the current running scope.

As you wanted to access the ng-repeat $index of outer ng-repeat in inner ng-repeat, you could use $parent.$index to indicate parent 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>

Though the cleaner solution to solve this problem would be, use ng-init on outer ng-repeat and have outer index in scope variable, by which you can get rid of $parent keyword.

<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>
Comments