I've got the following json data returned from a service request:
{ "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName": "Masm" }] }], "count": 2 }
And I am trying the following code in html to loop through this data:
<option ng-repeat="entry in entries" value="{{entry.name}}">{{entry.name}}</option>
I get the following error when I run the code:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: entry in entries, Duplicate key: string:c
Following is the code for my controller:
myApp.controller("MyController", ['$scope', '$http', '$log', function($scope, $http, $log){ ... $http.get('https://myServiceURL').success(function(data){ $scope.entries = data; }); }]);
Could somebody help me understand why am I getting that error?
You can use unique filter while using ng-repeat . If you use track by $index then unique won't work.
Definition and Usage 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. Note: Each instance of the repetition is given its own scope, which consist of the current item.
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using 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.
Add track by $index
to your ng repeat so instead of:
<option ng-repeat="entry in entries" value="{{entry.name}}">{{entry.name}}</option>
Try:
<option ng-repeat="entry in entries track by $index" value="{{entry.name}}">{{entry.name}}</option>
There's further information about this in the documentation for this error message:
Occurs if there are duplicate keys in an ngRepeat expression. Duplicate keys are banned because AngularJS uses keys to associate DOM nodes with items.
By default, collections are keyed by reference which is desirable for most common models but can be problematic for primitive types that are interned (share references).
Your JSON is invalid and should be :
{ "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }, { "id": 8029, "name": "Mas", "niceName": "Masm" }], "count": 2 }
Also, make sure you are accessing the document at the right level, use :
$http.get('https://myServiceURL').success(function(data){ $scope.entries = data.entries; });
Then, it should work. See this JSBin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With