Filtering on object map rather than array in AngularJS

前端 未结 6 2145
伪装坚强ぢ
伪装坚强ぢ 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:23

    I would change my data structure to an array. Anyway, here's another implementation to filter your friends object.

    angular.module('filters',['utils'])
      .filter('friendFilter', function(utils){
    
        return function(input, query){
          if(!query) return input;
          var result = [];
    
          angular.forEach(input, function(friend){
            if(utils.compareStr(friend.name, query) ||
               utils.compareStr(friend.phone, query))
              result.push(friend);          
          });
          return result;
        };
      });
    

    This iterates over the object only once, compares by name and phone and can be called like this.

  • I defined the compareStr in another module, but you don't really need to do it.

    angular.module('utils', [])
      .factory('utils', function(){
        return{
          compareStr: function(stra, strb){
            stra = ("" + stra).toLowerCase();
            strb = ("" + strb).toLowerCase();
            return stra.indexOf(strb) !== -1;
          }
        };
      });
    

    Don't forget to inject the filters module into your app

    angular.module('app',['filters'])
    

    Here's the full example: http://jsbin.com/acagag/5/edit

提交回复
热议问题