如何在AngularJs中使用ng-repeat重复重复的对象?

前端之家收集整理的这篇文章主要介绍了如何在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",{"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)

添加后我有重复的对象.因为我想在angularjs.First中使用ng-repeat重复标签名称,我有这样的输出

输出: –

name   textBox
email  textBox

添加按钮后单击输出: –

name   textBox
email  textBox
name   textBox

解决方法

使用$index跟踪

var app = angular.module("app",[])
app.controller('ctrl',['$scope',function($scope){
       $scope.data=[];
$scope.data=[{"label":"name","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>

猜你在找的Angularjs相关文章