How to make ng-repeat filter out duplicate results

前端 未结 16 3037
鱼传尺愫
鱼传尺愫 2020-11-22 06:52

I\'m running a simple ng-repeat over a JSON file and want to get category names. There are about 100 objects, each belonging to a category - but there are only

16条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 07:12

    None of the above filters fixed my issue so I had to copy the filter from official github doc. And then use it as explained in the above answers

    angular.module('yourAppNameHere').filter('unique', function () {
    

    return function (items, filterOn) {

    if (filterOn === false) {
      return items;
    }
    
    if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
      var hashCheck = {}, newItems = [];
    
      var extractValueToCompare = function (item) {
        if (angular.isObject(item) && angular.isString(filterOn)) {
          return item[filterOn];
        } else {
          return item;
        }
      };
    
      angular.forEach(items, function (item) {
        var valueToCheck, isDuplicate = false;
    
        for (var i = 0; i < newItems.length; i++) {
          if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
            isDuplicate = true;
            break;
          }
        }
        if (!isDuplicate) {
          newItems.push(item);
        }
    
      });
      items = newItems;
    }
    return items;
      };
    
    });
    

提交回复
热议问题