Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 350
trainoasis Avatar asked Nov 04 '14 18:11

trainoasis


People also ask

How do I use track in NG-repeat?

Track by $index in AngularJSThe ngRepeat track by $index allows you to specify which items should be repeated using their index number. The ngRepeat is a directive that can be added to the HTML template of an Angular application. It is used for creating lists, and it can take an expression as an argument.

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What is the use of NG-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object.


1 Answers

$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

like image 113
Anthony Chu Avatar answered Sep 17 '22 15:09

Anthony Chu