Filtering on object map rather than array in AngularJS

前端 未结 6 2121
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 05:15

Given a controller with a $scope property that is an object with other properties rather than an array like below, how should I filter the ng-repeat set?

6条回答
  •  温柔的废话
    2020-12-03 05:46

    I had the same problem, and succeeded by creating my own filter that accepts a map, while still using the built-in filter for doing the actual matching.

    My custom filter traverses the map, and for each element calls the built-in filter, but given that that filter only accepts an array, I wrap each element in an array of length 1 (the [data] below). So the match succeeds if the output-array's length is still 1.

    .filter('mapFilter', function($filter) {
      var filter = $filter('filter');
    
      return function(map, expression, comparator) {
        if (! expression) return map;
    
        var result = {};
        angular.forEach(map, function(data, index) {
          if (filter([data], expression, comparator).length)
            result[index] = data;          
        });
    
        return result;
      }
    })
    

    This setup loses efficiency of course because the built-in filter is required to determine what it needs to do for each element in the map, instead of only once if you give it an array with all elements, but in my case, with a map of 500 elements the filtering is still instanteanous.

提交回复
热议问题