61

I need a second $index for my nested ng-repeat loop. How and where should I put it?

AngularJS site says

Creating aliases for these properties is possible with ngInit. This may be useful when, for instance, nesting ngRepeats.

<div ng-repeat="person in persons track by $index">
    <div ng-repeat="something in array track by $index2"> <!-- where to init this and how to manage it?-->

If I use $index again, it seems to work but I am not sure this is the right thing? I am sure there is an easy and correct way of doing it, I just wasn't able to find an example.

Thanks

trainoasis
  • 6,419
  • 12
  • 51
  • 82

1 Answers1

150

$index will refer to the index on the innermost ngRepeat scope, so if that's what you need, you can just use it.

What the docs is describing is a scenario where you need access to $index in the parent ngRepeat. You can get it in a couple of ways: One is to use $parent, and another is to use ngInit, as the Angular docs suggested. Here's an example...

<li ng-repeat="thing in things" ng-init="parentIndex = $index">
    {{ $index }}
    <ul>
        <li ng-repeat="value in thing.values">
            {{ value }} 
            {{ $index }} <!-- inner $index -->
            {{ $parent.$index }} <!-- parent $index -->
            {{ parentIndex }} <!-- also parent $index -->
        </li>
    </ul>
</li>

Fiddle

Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
  • Exactly what I wanted to know. Was a bit confused with the docs. Thank you – trainoasis Nov 04 '14 at 18:51
  • Worth noting is that it works for any javascript object available. I used it to create an alias for the outer loops $last boolean to make it available in the inner loop. – Skurpi Aug 06 '15 at 11:01
  • 5
    By very very very careful with this approach if you intend to delete any list items later on from the array. For example, if you delete any array items from the array `things`, then $index will update itself to reflect the new state of the array, but `parentIndex` will still point to the index of the deleted item. This will be huge problem when it comes to deletion. The `parentIndex` will reflect correctly once you have saved the state & refreshed the page i.e. you have to re-render the array list in order to show updated indices. I figured this after struggling with it for 3 days. – Devner Jul 29 '16 at 18:03
  • I have a complicated structure where in i am creating Forms using nested For Loops. For me 'ng-init' solved this issue. Thank you. – mulla.azzi Aug 17 '16 at 05:39
  • Thanks for this. Can't believe I will get hired and work on AngularJS this year 2022 but yeah this saved my nested repeat custom directive. Thanks again – leipzy Jul 13 '22 at 07:39
  • 1
    Cannot stress enough the importance of @Devner warning regarding using this approach if you are deleting objects from an array based on the index. It will not work. I struggled with the same issue – Push W. Aug 29 '22 at 16:53