Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 add button push one more object into $scope.data array like

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

In the above 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 output like this

OutPut:-

name   textbox
email  textbox

After add button click Output:-

name   textbox
email  textbox
name   textbox
like image 936
durga siva kishore mopuru Avatar asked Jan 06 '23 09:01

durga siva kishore mopuru


1 Answers

use track by $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>
like image 63
Hadi J Avatar answered Feb 23 '23 04:02

Hadi J