2016-03-30 36 views
-1

我有一個數組,其中假設有5個值存在示例(1,2,3,4,5); 現在對這個數組執行一些操作後,現在我的數組變成(1,2,3,4,5,1,2,3,4,5)現在我想用ng-repeat與$ index並且希望重複的數據將只顯示一次。有可能嗎?

+0

你想只顯示1,2,3,4,5嗎? – user7

回答

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-重複使用它

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

請參閱本plnkr例如https://plnkr.co/edit/wklSOYJpHZxFlzCNPI9L?p=preview

+0

謝謝工作很好.... –

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> 
相關問題