Ng-repeat add elements (AngularJs 1.2.26)

I am testing code with ng-repeat, But with the old version of angular it works, but with the latest version it does not work!

I explain:

I am testing this code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.0/angular.js"></script> <div ng-app="myApp"> <div ng-controller="MyCtrl"> <ul> <li ng-repeat="item in items">{{item}}</li> </ul> <input ng-model="newItem" type="text"></input> <button ng-click="add(newItem)">Add</button> </div> </div> <script> var app = angular.module('myApp', []); app.controller('MyCtrl', function($scope) { $scope.items = ["A", "B", "C", "D"]; $scope.add = function(item) { $scope.items.push(item); }; }); </script> 

When I add severarls elements, it works great! with version angular.js / 1.1.0 It adds a new element

But this will not work with the latest version! We can add one element, but if we add several elements, it will make this error:

Error: [ngRepeat: dupes] Duplicates in the relay are not allowed. Use the expression "track by" to specify unique keys. Repeater: element in elements, duplicate key: string: d

So my question is: how to add news posts to ng-repeat with news versions?

Thanks!

+5
source share
2 answers

See here https://docs.angularjs.org/error/ngRepeat/dupes

add to your ng-repeat track by $index .:

 <li ng-repeat="item in items track by $index"> 

Demo below:

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="MyCtrl"> <ul> <li ng-repeat="item in items track by $index">{{item}}</li> </ul> <input ng-model="newItem" type="text"></input> <button ng-click="add(newItem)">Add</button> </div> </div> <script> var app = angular.module('myApp', []); app.controller('MyCtrl', function($scope) { $scope.items = ["A", "B", "C", "D"]; $scope.add = function(item) { $scope.items.push(item); }; }); </script> 
+10
source

It works, but if you add a key already contained in the array, it will not be able to recognize unique elements (because they are the same).

To fix this, you should use:

  <li ng-repeat="item in items track by $index" 

http://jsfiddle.net/v87kgwud/

+2
source

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


All Articles