【问题标题】:How to repeat duplicate objects using ng-repeat in AngularJs?如何在 AngularJs 中使用 ng-repeat 重复重复对象?
【发布时间】:2016-03-25 05:55:20
【问题描述】:

这是我的代码。

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

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

输出:-

name   textbox
email  textbox

添加按钮后点击输出:-

name   textbox
email  textbox
name   textbox

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    使用 $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>

    【讨论】:

    • 谢谢@hadiJZ。我有这样的数据 $scope.data=[{"label":"name","type":"textbox"},{"label":"name","type":"textbox"}];当我在第一个文本框中输入数据并在第二个文本框中也生效时。我在文本框中使用 ng-model 。那么如何区分这两个文本框。
    • 这个答案可能对你有帮助stackoverflow.com/questions/32470928/…
    【解决方案2】:

    将此purpose 使用track by

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

    但是避免在ng-options和其他情况下使用select as .. for ...构造时使用track byread more

    JsFiddle here

    【讨论】:

    • 检查 jsFiddle 后,我放置了 ng-model="eachItem.value"
    • @durgasivakishoremopuru tnx,更新小提琴链接
    【解决方案3】:

    您必须确保数组中的项目具有唯一键。如果这不可能,您可以在 ng-repeat 中使用 track by $index

    查看详情here

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 2014-07-05
      • 2014-04-14
      • 1970-01-01
      • 2015-09-25
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      相关资源
      最近更新 更多