How To Add RegEx In Angular Filter
Example: plunker From the above example, I have created a simple form with filter option using angular. As far as the filter concern, it's a default filter which is provided by ang
Solution 1:
In this case I would probably create a custom filter.
The tricky part here is that your object model is not flat, so we have to do a deep traversal to check the fields. The caveat to this approach is that you could potentially be checking against fields that are not visible (although i believe this is how the default angular filter behaves).
If that is an issue, you could adjust the filter to pass in a list of fields to check against and use those to filter out unwanted fields.
Here is the filter :
app.filter('wildcard', function() {
return function(list, value) {
if (!value) {
return list;
}
var escaped = value.replace(/([.+?^=!:${}()|\[\]\/\\])/g, "\\$1");
var formatted = escaped.replace('*', '.*')
if (formatted.indexOf('*') === -1) {
formatted = '.*' + formatted + '.*'
}
var output = []
angular.forEach(list, function(item) {
var regex = new RegExp('^' + formatted + '$', 'im');
if (traverse(item, regex)) {
output.push(item);
}
});
return output
}
function traverse(item, regex) {
for (var prop in item) {
//angular property like hash
if(prop[0] === '$$'){
return;
}
var value = item[prop];
if (typeof value === 'object') {
traverse(value, regex);
}
if(regex.test(value)){
return true;
}
}
}
})
And then in you html :
<tr ng-repeat="d in data | wildcard:search">
Post a Comment for "How To Add RegEx In Angular Filter"