I would like to create AngularJS Filter Using Lodash to Achieve global search with multiple keyword. I already tried .contains() , .contains() , _.filter() but really can't get it working.
ANGULARJS FILTER
.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
});
}
}
})
VIEW
<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);
});
That should do it.
If you want this search to be recursive I recommend using the deepFilter
extension I created here: https://github.com/AndrewHenderson/underscore.deep
try
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;
}
}
});
Here is a working Demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.