Angularjs ng-repeat array - duplicate values

So, I am just starting with angular JS and am a bit confused with ng-repeat when working with arrays. The code below does not work as it is ... but when I change dayNames to an object and give it a pair of key values, this is normal.

var myApp = angular.module('exampleApp', []); myApp.controller("dayCtrl",function($scope){ $scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"]; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!DOCTYPE html> <html ng-app="exampleApp"> <head> <script src="angular.js"></script> <script src="controller.js"></script> </head> <body ng-controller="dayCtrl"> <h2>Hello, these are the days of the week</h2> <ul> <li ng-repeat="day in dayNames">{{day}}</li> </ul> </body> </html> 
+6
source share
1 answer

This does not work because you have duplicates in the array. When you repeat an array of primitives, the unique default key used by angular to bind an element in an array to a DOM element is an element in the array itself. And of course, in your case, this is not unique, and it causes duplication in the repeater error.

You can avoid this by using also track by $index , which makes the index an identifier.

 ng-repeat="day in dayNames track by $index" 

When using an array of objects (without tracking), angular adds a unique identifier to the new $$hashkey property for each element of the array. This property is then used as a key to the associated DOM elements with the corresponding array element by identifier. Moving the same object to an array would move the DOM element in the same way in the DOM. Therefore, when you use an array of objects, you do not see any problems, because all these hashkeys are unique.

 var myApp = angular.module('exampleApp', []); myApp.controller("dayCtrl",function($scope){ $scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"]; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!DOCTYPE html> <html ng-app="exampleApp"> <head> <script src="angular.js"></script> <script src="controller.js"></script> </head> <body ng-controller="dayCtrl"> <h2>Hello, these are the days of the week</h2> <ul> <li ng-repeat="day in dayNames track by $index">{{day}}</li> </ul> </body> </html> 
+15
source

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


All Articles