javascript - AngularJS Ng-重复和重复

标签 javascript angularjs

我在 SO 中看到很少有问题讨论在 ng-repeat 中不允许重复。我的问题有点不同。就我而言,我很困惑,因为我即使数组中有重复的对象也没有收到错误

这是我的 HTML 代码

<table>
      <tr ng-repeat="item in items">
        <td> {{ item.email}}</td>           
      </tr>
</table>

下面是填充数组的代码

app.controller('MainCtrl', function($scope) {


$scope.items=[];

  $scope.items.push({
           "id":"1",
           "email":"a@b.com"});
  $scope.items.push({
           "id":"1",
           "email":"a@b.com"});

  $scope.items.push({
           "id":"2",
           "email":"x@y.com"});
  $scope.items.push({
           "id":"2",
           "email":"x@y.com"});


});

根据我的理解我应该得到错误并且数组中有重复的对象

然而它得到了完美的呈现。这是plunker链接

ng-repeat-demo

显然我缺少一些基本的东西。有人可以指出我理解上的差距吗?

编辑

这是我在我的应用程序中遇到的情况(出于明显的原因,仅更改了电子邮件 ID)

ExampleApp.filter("extractEmail", function (){

  return function(items){
    //console.log("test" + input[0].highlight.file[0]);
    var filtered = [];

    console.log(" items == " + items);


    angular.forEach(items, function(item){

      if (item){
        var obj = item.highlight.file[0].toString().match(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/);

      if (obj) {
        //console.log(obj[0]);
        filtered.push(obj[0]);
      }

      }


    }); 

    console.log(filtered);
    return filtered;
  }

});

我的 console.log 打印 [“a@gmail.com”、“a@gmail.com”、“b@gmail.com”、“b@gmail.com”]

我得到的错误

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: x in clusterState| extractEmail, Duplicate key: string:a@b.com, Duplicate value: “a@b.com"

我用类似的代码更新了 plunker。无法重现

第二次编辑

问题出在我使用的版本上: Angular JS 1.0.x 支持重复无法重现 http://plnkr.co/edit/qrOez7aZ7X1jsOrmkfiP?p=preview

使用更高版本能够重现

http://plnkr.co/edit/q3oPCrW3RepxvWSZ1LB1?p=preview

最佳答案

javascript 中的对象是通过引用进行比较,而不是通过值进行比较。
一个对象的内容是否与另一个对象完全相同并不重要,如果引用不指向同一个对象,它们就是不同的。
例如:

// In this case "var a" and "var b" points to different objects.
var a = {};
var b = {};

a == b; // false

// Here, they points to the same one
var a = {};
var b = a;

a == b; // true

如果您需要每个条目都不同,您必须自己检查每个条目。
Angular ngRepeat 有一个语法变体,它使用 track by 让您决定哪个条目是不同的(或重复的)。

<div ng-repeat="entry for entries track by entry.id">{{entry.email}}</div>

关于javascript - AngularJS Ng-重复和重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30277888/

相关文章:

javascript - AngularJS 测试,找不到我的 Controller

javascript - AngularJS UI Router 多次加载同一个 Controller

javascript - 如果 div 因溢出而隐藏,则滚动

javascript - 给一个html元素添加一串html属性

javascript - 关于 Ext.define() 中 initComponent() 的最佳实践

javascript - Loopback.io 多重包含模型查询条件

javascript - ng-model 具有字符串值和 ng-option 整数

javascript - Angular 模式和 ng 模型错误

javascript - 使用 Angular JS 的 HTML5 进度条在 Microsoft Edge 上不显示值

javascript - 将两种功能合二为一,用于剑道网格