2

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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
andresmijares
  • 3,658
  • 4
  • 34
  • 40
  • Possible duplicate of [How to access the index of super parent in nested ng-repeats](http://stackoverflow.com/questions/31006962/how-to-access-the-index-of-super-parent-in-nested-ng-repeats) – romario333 Jun 29 '16 at 05:10

2 Answers2

3

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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Cleaner solution is to use ng-init, see http://stackoverflow.com/questions/31006962/how-to-access-the-index-of-super-parent-in-nested-ng-repeats – romario333 Jun 29 '16 at 05:11
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>

Output:

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
LameCoder
  • 1,287
  • 7
  • 22