'When I try to run through an array, the array behaves like a set, by which I mean that if I put two equal values in, the program crashes
I am doing a AngularJS program, in which I want to run through an array. Here is my program:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Array: {{t}}</p>
<span style="margin:1px;background-color:cyan;" ng-repeat="x in names">
{{x}}
<span>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
// $scope.names = ["Emil", "Ellen", "Tobias", "Linus", "Poul", "Peter"];
$scope.names = ["Emil", "Emil", "Tobias", "Linus", "Poul", "Peter"];
$scope.t = angular.isArray($scope.names);
});
</script>
</body>
</html>
If I use the upper version of $scope.names, it works. When I take the lower one, it crashes. Both of them are arrays, according to isArray, so why doesn't it work?
Very confused.
Poul
Solution 1:[1]
ngRepeat does not support two equal values in the same array, you should use objects with a unique identifier, like this:
$scope.names = [{id: 0, name: 'Emil'}, {id: 1, name: 'Emil'}];
or you can use track by as shown in the following example.
More information about ngRepeat and $index property here
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Emil", "Tobias", "Linus", "Poul", "Peter"];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Array: {{t}}</p>
<!-- $index: This special property tracks the collection items by their index -->
<span style="margin:1px;background-color:cyan;" ng-repeat="x in names track by $index">
{{x}}
</span>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raxel21 |
