Remove duplicate from ng-repeat [duplicate]

一个人想着一个人 提交于 2019-12-06 01:54:27

You can use unique filter while using 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>

If you don't want to include Lodash, you can do this:

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

Try this loop :

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

Use lodash for convert your array to unque element array

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

To use loadsh you need to use cdn for lodash

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

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

To achieve expected result first sort and then filter with ng-if

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

code sample - 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!