如何使用Lodash创建AngularJS Filter实现多关键词全局搜索?

How to create AngularJS Filter Using Lodash to Achieve global search with multiple keyword?

我想创建 AngularJS 使用 Lodash 的过滤器以实现具有多个关键字的全局搜索。我已经试过 .contains(), .contains(), _.filter() 但真的无法正常工作。

ANGULARJS 过滤器

.filter('multiKeywordSearch', function() {
    return function(obj, keywords) {
        if((typeof keywords === 'undefined') || keywords == "") {
            return obj; 
        }
        else{
            var keywords = keywords.split(" ");

            return _.filter(obj, function(keywords){
                    return //I REALLY DON'T KNOW WHAT TO USE      
            });
        }
    }
})

查看

<input type="text" ng-model="search" class="form-control pull-right" placeholder="Search">

<tr ng-repeat="generalDocument in generalDocuments | orderBy: 'id' | multiKeywordSearch: search">
            <td>{{ $index + 1 }}</td>
            <td>{{ generalDocument.company.company_name }}</td>
            <td>{{ generalDocument.branch.branch_name }}</td>
            <td>{{ generalDocument.document_type }}</td>
            <td>{{ generalDocument.description }}</td>
var results = [];
var keywords = ["John", "Doe"];
_.filter(data, function(obj) {
  var status = true;
  for(var i in keywords) {
    if(!status) return;
    status = _.contains(obj, keywords[i]);
  }
  if(status) results.push(obj);
});

应该可以了。

如果您希望此搜索是递归的,我建议使用我在此处创建的 deepFilter 扩展:https://github.com/AndrewHenderson/underscore.deep

尝试

app.filter('multiKeywordSearch', function () {
    return function (collection, keywords) {
        if (!keywords) {
            return collection;
        } else {
            keywords = keywords.toUpperCase().split(" ");
            _.each(keywords, function (keyWord) {
                collection = _.filter(collection, function (item) {
                    for (var key in item) {
                        if (item.hasOwnProperty(key) && !(key.indexOf('$$hashKey') > -1)) {
                            if (typeof item[key] === 'string' && item[key].toUpperCase().indexOf(keyWord) > -1) {
                                return true;
                            }
                        }
                    }

                });
            });

            return collection;
        }
    }
});

这是一个有效的Demo