Angularjs ng-repeat array - duplicate values
It does not work as is because you have duplicates in the array. When you repeat array of primitives, the default unique key used by angular to associate the item in the array with the DOM element is the item in the array itself. And ofcourse in your case it is not unique and it causes duplicate in repeater error.
You could avoid this by using track by $index
as well, which makes the index to be the identifier.
ng-repeat="day in dayNames track by $index"
When you use array of objects (without track by) angular adds the unique id to a new property called $$hashkey
on each item of the array. This property is then used as a key to associated DOM elements with the corresponding item in the array by identity. Moving the same object in array would move the DOM element in the same way in the DOM. So when you use array of objects you do not see any issues, because all of those 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>
John23
Updated on June 23, 2022Comments
-
John23 almost 2 years
So I'm just starting with angular JS and am a little confused about ng-repeat when dealing with arrays. The below code doesn't work as is...but when I change dayNames to an object and give it key value pairs it's fine.
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>
-
John23 about 9 yearsWhen I remove the duplicate days in the array in my code above it still isn't working for some reason though.
-
PSL about 9 years@John23 Well you need to add angular for angular app to work. :) Look at the console.
-
PSL about 9 years@John23 Check the snippet in your question now.
-
John23 about 9 yearsI had a local variable name error after switching it back to the array from the object....was connected to angular via script element. Works perfect...thanks for the help.