How to repeat duplicate objects using ng-repeat in AngularJs?

This is my code.

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

This is my 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>

when i click the add button add another object to the array $scope.datalike

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

In the above message, I got an error

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 have duplicate objects after adding. because I want to repeat label names using ng-repeat in angularjs.First I have an output like this

Conclusion: -

name   textbox
email  textbox

After adding the button, click "Exit": -

name   textbox
email  textbox
name   textbox
+4
source share
3 answers

use track by index $ index

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>
Run codeHide result
+3
source

Use track byfor this.

<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

. track by ng-repeat, ng-repeat ( ).

track by ng-options , select as .. for ... ( )

JsFiddle

+3

, . , track by $index ng-repeat.

+2

All Articles