简体   繁体   English

AngularJS:如何过滤对象阵列除了一个属性

[英]AngularJS: How to filter Object Array Except one property

Angular $filter can do string fuzzy search for Object Array, Angular $ filter可以对Object Array进行字符串模糊搜索,

But every of My Objects have one property of base64 pic. 但是我的每个对象都有一个base64 pic的属性。

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


}],

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

How can I except pic property in fuzzy search? 我怎样才能在模糊搜索中除了pic属性?

Angular's filter can take a function as an argument to filter your array. Angular的过滤器可以使用函数作为过滤数组的参数。 The filter will select items that the function returns true for. 过滤器将选择函数返回true的项目。

You can use this feature to achieve what you want. 您可以使用此功能来实现您的目的。

Here is the official documentation 这是官方文档

So, you could do something like this to compare the search text only with the two properties you want to: 因此,您可以执行以下操作,仅将搜索文本与您想要的两个属性进行比较:

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. 这是展示这种效果的小提琴。

This is the way I ended up implementing it. 这是我最终实现它的方式。 Angular custom filters seem to be the way to go for this sort of problem. Angular自定义过滤器似乎是解决此类问题的方法。 You can find more about them from Angular , but in this implementation you can add any other fields you'd like to leave off by adding another && key != "unwantedKey" . 您可以从Angular中找到有关它们的更多信息 ,但在此实现中,您可以添加另一个&& key != "unwantedKey"来添加您想要放弃的任何其他字段。 The value of the key must be a string for the indexOf to work so the typeof portion makes sure we don't get any ids that are numbers, etc. key的值必须是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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM