从ng-repeat中删除重复项

时间:2018-03-13 03:07:34

标签: javascript html angularjs angularjs-ng-repeat

我有一个非常简单的数组,它有重复的值。我的阵列是这样的:

$scope.type= ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"]

在我的重复中,我有这个条件

ng-repeat = types in type track by $index

如何在ng-repeat中仅显示数组中的唯一值?

5 个答案:

答案 0 :(得分:6)

使用unique时,您可以使用ng-repeat过滤器。

ng-repeat="type in types|unique: type"



var app = angular.module('myApp',['ui.directives', 'ui.filters']);
app.controller("myCtrl", function($scope) {
  $scope.types = ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"];
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="type in types|unique: type">{{type}}</div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果您不想包含Lodash,可以这样做:

$scope.typeUnique = Object.keys($scope.type.reduce((acc, val) => { acc[val] = true; return acc; }, {}));

答案 2 :(得分:0)

使用lodash将数组转换为unque元素数组

$scope.type = _.uniq($scope.type);

要使用loadsh,您需要将cdn用于lodash

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>

https://lodash.com/docs/4.17.5#uniq

答案 3 :(得分:0)

试试这个循环:

$scope.type= ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"];

var output = [];


angular.forEach($scope.type, function(type, index) {

          // if it's not already part of our keys array
          if(output.indexOf(type) === -1) {
              // push this item to our final output array
              output.push(item);
          }
      });

答案 4 :(得分:0)

要获得预期结果,请先进行排序,然后使用ng-if

进行过滤
      <ul>
  <li ng-repeat="x in sortedType = (type | orderBy) track by $index" ng-if="sortedType[$index -1] != x">
        {{ x }}
      </li>
    </ul>

代码示例 - https://codepen.io/nagasai/pen/bvVMvV

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.type= ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"]
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">
  
  <ul>
 <li ng-repeat="x in sortedType = (type | orderBy) track by $index" ng-if="sortedType[$index -1] != x">
    {{ x }}
  </li>
</ul>

</div>
</body>
&#13;
&#13;
&#13;