NoteStylet
NoteStylet

Reputation: 325

ng-repeat add items (AngularJs 1.2.26)

I am testing a code with ng-repeat, But with the old version of angular, it's works, but with the latest version it doesn't work !

I explain :

I test 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 items, it works fine ! with the angular.js/1.1.0 version It add a new item

But with the latest version it doesn't work ! We can add one item, but if we add more than one item, it makes this error :

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: string:d

So my question is how can we add news items in ng-repeat with the news versions ?

Thanks !

Upvotes: 5

Views: 16612

Answers (2)

Michael
Michael

Reputation: 3326

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

To fix this, you have to use:

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

http://jsfiddle.net/v87kgwud/

Upvotes: 2

sylwester
sylwester

Reputation: 16498

Please see here https://docs.angularjs.org/error/ngRepeat/dupes

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

<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>

Upvotes: 10

Related Questions