2016-03-25 109 views
4

這是我的代碼。如何在AngularJs中使用ng-repeat重複重複的對象?

$scope.data=[]; 
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"}]; 
$scope.addFields = function (field) { 
    $scope.data.push(field); 
    }; 

這是我的html: -

<div ng-repeat="eachItem in data"> 
<input type="button" value="add" ng-click="addFields(eachItem)"/> 
    <label>{{eachItem.label}}</label> 
    <input type="text" ng-model="fieldValue"/> 
</div> 

當我點擊添加按鈕按下一個更對象爲$scope.data陣列狀

$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"},{"label":"name","type":"string"}]; 

在上面,我得到一個錯誤

angular.min.js:102 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.14/ngRepeat/dupes?p0=nestedField%20in%20fie…%2C%22type%22%3A%22string%22%2C%22%24%24hashKey%22%3A%22object%3A355%22%7D 
at Error (native) 

I添加後有重複的對象。因爲我想在angularjs.First採用NG-重複再重複的標籤名稱我有這樣

的輸出: -

name textbox 
email textbox 

之後添加按鈕,點擊輸出: -

name textbox 
email textbox 
name textbox 

回答

3

利用軌跡由$指數

var app = angular.module("app",[]) 
 
app.controller('ctrl',['$scope', function($scope){ 
 
     $scope.data=[]; 
 
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"}]; 
 
$scope.addFields = function (field) { 
 
    $scope.data.push(field); 
 
    }; 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl"> 
 
<div class="item item-checkbox"> 
 
    <div ng-repeat="eachItem in data track by $index"> 
 
<input type="button" value="add" ng-click="addFields(eachItem)"/> 
 
    <label>{{eachItem.label}}</label> 
 
    <input type="text" /> 
 
</div>  
 
</div>

+0

謝謝你@hadiJZ。我有數據像這樣$ scope.data = [{「label」:「name」,「type」:「textbox」},{「label」:「name」,「type」:「textbox」}];當我在第一個文本框中輸入數據,並且也在第二個文本框中生效時。我在文本框中使用ng-model。那麼如何區分這兩個文本框。 –

+0

這個答案可能會幫助你http://stackoverflow.com/questions/32470928/angular-formly-adding-form-fields-dynamically-on-user-click/35603088#35603088 –

3

使用track by爲此purpose

<div ng-repeat="eachItem in data track by $index"> 
<input type="button" value="add" ng-click="addFields(eachItem)"/> 
    <label>{{eachItem.label}}</label> 
    <input type="text" ng-model="eachItem.value" /> 
</div> 

您也可以使用track by與自定義歸檔,像id,或任何

重要:這是更好地在每個ng-repeat使用track by,因爲它是提高ng-repeat的性能(read more) 。

但要避免當您使用select as .. for ...建設read more

JsFiddle here

+0

檢查一次的jsfiddle,我把NG-模型= 「eachItem.value」 –

+0

@durgasivakishoremopuru TNX,更新鏈接到小提琴 –

2

你必須確保數組中的項具有唯一鍵使用track byng-options等案件。如果這是不可能的,你可以在ng-repeat中使用track by $index

檢查細節here