从 ng-repeat 中删除重复项

Remove duplicate from ng-repeat

我有一个非常简单的数组,其中包含重复值。我的数组是这样的:

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

在我的 ng-repeat 中,我有这种情况

ng-repeat = types in type track by $index

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

使用 lodash 将数组转换为唯一元素数组

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

要使用 lodash,您需要为 lodash 使用 cdn

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

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

试试这个循环:

$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);
          }
      });

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

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

您可以在使用 ng-repeat 的同时使用 unique 过滤器。

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>

为了达到预期的结果,先排序,然后用 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

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"]
});
<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>