AngularJS: ng-repeat track by $index inside nested loops

AngularjsAngularjs Ng-Repeat

Angularjs Problem Overview


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

Angularjs Solutions


Solution 1 - Angularjs

$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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrainoasisView Question on Stackoverflow
Solution 1 - AngularjsAnthony ChuView Answer on Stackoverflow