javascript - AngularJS: How to filter Object Array Except one property - Stack Overflow

Angular $filter can do string fuzzy search for Object Array, But every of My Objects have one property

Angular $filter can do string fuzzy search for Object Array,

But every of My Objects have one property of 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?

Angular $filter can do string fuzzy search for Object Array,

But every of My Objects have one property of 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?

Share Improve this question edited May 31, 2014 at 6:28 Charles 51.5k13 gold badges106 silver badges144 bronze badges asked May 30, 2014 at 15:31 Chen-Tsu LinChen-Tsu Lin 23.3k16 gold badges56 silver badges65 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

Angular's filter can take a function as an argument to filter your array. The filter will select items that the function returns true for.

You can use this feature to achieve what you want.

Here is the official documentation

So, you could do something like this to pare 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. 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". 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.

$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;
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745467160a4628967.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信