NgRepeat: dupes - duplicates in the repeater with ngrepeat nested and blank lines

I am working with angular creating a data table that comes from a JSON API call. I need to use nested ngRepeat, but I see strange results when whole table rows are missing, when a row has a couple of empty rows.

I can reproduce with the following plow. http://plnkr.co/edit/VCzzzPzfgJ95HmC2f83P?p=preview

<script> function MyController($scope){ $scope.test = {"rows":[ ["one","two","three"], ["one","two","three"], ["one","","three"], ["one","",""], ["","two",""], ["","","three"], ["one","two","three"], ["one","two","three"], ]};}; </script> <div ng-app ng-controller="MyController"> <table> <tr ng-repeat="(key,ary) in test.rows"> <td>{{key}}</td> <td ng-repeat="value in ary">{{value}}</td> </tr> </table> </div> 

Please note that the array has two empty lines, ngRepeat nested ones do not work.

I've gone crazy? Is there any explanation for this?

+6
source share
1 answer

Yes. You will need to use track by $index as you repeat the primitives or convert it to an array of objects. Reason: ng-repeat creates a unique id $$hashkey (and is bound to the property of the repeated object as a property) for each of the iterated values, if it is an object (if you do not specify something as a track).

In your case, you have primitives, so it cannot attach the property itself, so it tries to consider values ​​repeated as identifiers, and finds duplicates when you repeat several empty lines. You will see the same effect when you repeat an array of objects with more than one of them: undefined or zero.

So in this case, you can use the $index track. Thus, duplicate items will be tracked by its index.

 <td ng-repeat="value in ary track by $index">{{value}}</td> 

Demo

A much better option is to convert it to an array of objects so that you do not encounter such problems. If you have a property that uniquely identifies a repeating element (say id ), you can set it as the track by property. When you restore an array (or update an array), angular uses a tracked identifier to determine whether it needs to remove an element from the DOM and recreate it or simply update an existing element. In many cases, when the list is updated, the list of elements is always advisable to use a track with an identifier on the object repeated for work efficiency.

+9
source

Source: https://habr.com/ru/post/976127/


All Articles