【问题标题】:ng-repeat track by $index display the item only once if the similar key exists multiple times in angularjsng-repeat track by $index 如果相似的键在 angularjs 中多次存在,则仅显示一次该项目
【发布时间】:2018-11-28 08:41:59
【问题描述】:

我的 angularjs 代码中出现 [ngRepeat:dupes]: 错误。 所以我在stackoverflow上搜索并找到了使用$index跟踪的解决方案。这现在对我有用。但是,如果多次出现相同的键,它会多次显示该项目。如果同一个键多次存在,我只想显示一个项目。 这是我的示例代码:

<div ng-repeat="user in users | filter:myFilter track by $index">
</div>

这是当前的输出:

为了显示这两张卡片,我希望代码只显示一张卡片,因为它们都是相同的。 我该怎么做?

【问题讨论】:

  • 你错过了“并且在用户跟踪中使用用户 $index | filter:myFilter 我可以帮助你。
  • 我在用户跟踪中编辑了问题和用户 $index |过滤器:myFilter 不起作用
  • 为什么不在将列表传递给 ng-repeat 之前删除重复项?
  • 请显示您的用户数组,一次

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

将数组传递给函数并创建一个没有重复值的数组 像 myFunction(users) 这样重复部分将变为 ng-repeat="user in myFunction(users)"。自己写函数。

【讨论】:

  • 请看我的问题here
【解决方案2】:

我通过创建过滤器来修复它:

var app = angular.module('angularTable', []);

app.filter('unique', function() {
   // we will return a function which will take in a collection
   // and a keyname
   return function(collection, keyname) {
      // we define our output and keys array;
      var output = [],
          keys = [];

      // we utilize angular's foreach function
      // this takes in our original collection and an iterator function
      angular.forEach(collection, function(item) {
          // we check to see whether our object exists
          var key = item[keyname];
          // if it's not already part of our keys array
          if(keys.indexOf(key) === -1) {
              // add it to our keys array
              keys.push(key);
              // push this item to our final output array
              output.push(item);
          }
      });
      // return our array which should be devoid of
      // any duplicates
      return output;
   };
});

app.controller('listdata', function($scope, $http) {

your controller logic for the users array
   });

});

在视图中:

<div ng-repeat="user in users |unique:'name' | filter:myFilter track by $index">
</div>

【讨论】:

  • 使用函数比使用过滤器更好,因为过滤器会被多次调用,但函数不会。看我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多