2014-11-05 28 views
5

我正在用ng-repeat測試一個代碼, 但是使用老版本的angular,它是可行的,但是使用最新版本它不起作用!ng-repeat add items(AngularJs 1.2.26)

我解釋一下:

我測試此代碼:

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

當我添加severarls項目,它工作正常!與angular.js/1.1.0版本 它添加一個新項目

但與最新版本它不起作用! 我們可以添加一個項目,但如果我們增加一個以上的項目,它使這個錯誤:

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

所以我的問題是我們如何能夠在NG-重複添加與新聞版本的新聞項目?

謝謝!

+1

答案就在問題! :)使用'軌道由',像這裏:http://stackoverflow.com/questions/26232764/angularjs-nested-ng-repeat-array-in-object-only-works-if-there-is-one-item -in/26232889#26232889 – Cherniv 2014-11-05 10:42:05

回答

10

請看這裏https://docs.angularjs.org/error/ngRepeat/dupes

添加到您的ng-repeattrack by $index即:低於

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

演示:

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

2

它可以工作,但是如果你添加一個已經包含在數組中的密鑰,它將無法識別唯一的項目(因爲它們是相同的)。

爲了解決這個問題,你必須使用:

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

http://jsfiddle.net/v87kgwud/