在$ index中的ng-repeat轨道

时间:2016-03-30 16:47:31

标签: angularjs

我有一个数组,假设有5个值,例如(1,2,3,4,5); 现在用这个数组执行一些操作之后我的数组变成了(1,2,3,4,5,1,2,3,4,5)现在我想用$ index使用ng-repeat并希望重复的数据会只有一次出现。有可能吗?

2 个答案:

答案 0 :(得分:1)

您必须创建自定义过滤器以从列表中删除重复项。它可以是下面的东西

app.filter('unique', function() {

  return function(list) {

    var unique = function(origArr) {
      var newArr = [],
          origLen = origArr.length,
          found, x, y;

      for (x = 0; x < origLen; x++) {
          found = undefined;
          for (y = 0; y < newArr.length; y++) {
              if (origArr[x] === newArr[y]) {
                  found = true;
                  break;
              }
          }
          if (!found) {
              newArr.push(origArr[x]);
          }
      }
      return newArr;
    };

    return unique(list);

  }

});

然后将其与ng-repeat

一起使用
<p ng-repeat="item in list | unique">List Item: {{ item }}</p>

请参阅此plnkr示例https://plnkr.co/edit/wklSOYJpHZxFlzCNPI9L?p=preview

答案 1 :(得分:1)

只需创建一个角度过滤器即可获取唯一项目 - JSFiddle Reference

var app = angular.module("app", []);
app.controller("mainCtrl", function($scope) {
  $scope.items = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6];
});

app.filter("uniqueItem", function() {
  return function(collection) {
    var output = [];
    angular.forEach(collection, function(item) {
      if (output.indexOf(item) === -1) {
        output.push(item);
      }
    });
    return output;
  };
});

<div ng-repeat="item in items | uniqueItem">List Item: {{ item }}</div>