【问题标题】:AngularJS: How to filter Object Array Except one propertyAngularJS:如何过滤除一个属性外的对象数组
【发布时间】:2014-07-20 10:14:13
【问题描述】:

Angular $filter 可以对 Object Array 进行字符串模糊搜索,

但我的每个对象都有一个 base64 pic 属性。

var MyObjects = [{
    property1: 'ab',
    property2: 'cd',
    pic: '4AAQSkZJRgABAQEASABIAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBw.....' 
}, {
    property1: 'ef',
    property2: 'gh',
    pic: '4AAQSkZJRgABAQEASABIAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBw.....' 
}, {
    ....


}],

result = $filter('filter')(MyObjects, $scope.searchText);

如何在模糊搜索中排除 pic 属性?

【问题讨论】:

    标签: javascript angularjs angularjs-filter


    【解决方案1】:

    Angular 的过滤器可以将一个函数作为参数来过滤你的数组。过滤器将选择函数为其返回 true 的项目。

    您可以使用此功能来实现您想要的。

    Here is the official documentation

    因此,您可以执行以下操作来仅将搜索文本与您想要的两个属性进行比较:

    var filterFunction = function(item) {
        var val = $scope.searchText
        return item.property1.indexOf(val || '') !== -1 || item.property2.indexOf(val || '') !== -1;
    }
    
    result = $filter('filter')(MyObjects, filterFunction, $scope.searchText);
    

    Here's a fiddle demonstrating this effect.

    【讨论】:

      【解决方案2】:

      这就是我最终实现它的方式。 Angular 自定义过滤器似乎是解决此类问题的方法。 You can find more about them from Angular,但在此实现中,您可以通过添加另一个 && key != "unwantedKey" 来添加您想要保留的任何其他字段。键的值必须是 indexOf 工作的字符串,因此 typeof 部分确保我们不会得到任何数字等的 id。

      $scope.search = function(item){ 
          for (var key in item){
              if (typeof key === "string" && key != "pic"){ 
      
                  if(item[key].indexOf($scope.query) > -1){
                      return true;
                  }
              }
          }
          return false;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 2019-08-22
        相关资源
        最近更新 更多