I'm working through the AngularJS tutorial, and understand the basics of
However, the out of the box implementation seems limited to just filter the list of items to the exact word or phrase entered in .
Example: if the query is "table cloth", the result list can include a result with this phrase, "Decorative table cloth", but won't include "Decorative cloth for table" because the filter is just a continuous search string.
I know there's the ability to add custom filters, but at first glance it seems like those are mainly transforms.
Is there any way to add a custom filter so that both "Decorative cloth for table" and "Decorative table cloth" show up in the filtered result set?
Please see surfbuds answer below as it is superior
Just roll with your own filter:
.filter("myFilter", function(){
return function(input, searchText){
var returnArray = [];
var searchTextSplit = searchText.toLowerCase().split(' ');
for(var x = 0; x < input.length; x++){
var count = 0;
for(var y = 0; y < searchTextSplit.length; y++){
if(input[x].toLowerCase().indexOf(searchTextSplit[y]) !== -1){
count++;
}
}
if(count == searchTextSplit.length){
returnArray.push(input[x]);
}
}
return returnArray;
}
});
jsfiddle: http://jsfiddle.net/Cq3PF/
This filter makes sure that all search words are found.
Some improvements to the above custom filter:
Instead of using a loop within a loop, counts, and indexOf, this one uses regular expressions to achieve a logical AND and also a logical OR depending on the third argument to the filter (input array of strings, search terms, AND or OR).
Have a look at the forked Fiddle with the two types of filter and results:
http://jsfiddle.net/jonjon/Cx3Pk/23/
angular.module('app', [])
.filter("myFilter", function () {
return function (input, searchText, AND_OR) {
var returnArray = [],
// Split on single or multi space
splitext = searchText.toLowerCase().split(/\s+/),
// Build Regexp with Logical AND using "look ahead assertions"
regexp_and = "(?=.*" + splitext.join(")(?=.*") + ")",
// Build Regexp with logicial OR
regexp_or = searchText.toLowerCase().replace(/\s+/g, "|"),
// Compile the regular expression
re = new RegExp((AND_OR == "AND") ? regexp_and : regexp_or, "i");
for (var x = 0; x < input.length; x++) {
if (re.test(input[x])) returnArray.push(input[x]);
}
return returnArray;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With