Parameterized Custom Filter in AngularJs
Most of the times we need to filter the results in the specified attributes. We can achieve the same by following custom filter in angular.js
testModule.service('ViewModel',function(){
return {
this.Results:[{Name:'',Age:'',DateOfBirth:'',Addess:{Line1:'',Line2:'',PostCode:''},Designation:''}],
this.FilterBy:'',
this.FilterCommand : function () {
if (this.FilterBy) {
this.FilteredResults = $filter('fieldFilter')(this.Results, this.FilterBy, ['Name', 'Address', 'DateOfBirth']);
} else {
this.FilteredResults = this.Results;
}
};
}
});
testModule.filter('fieldFilter',['$filter', function ($filter) {
return function (input, filterby, parameters) {
var result = [];
var search = function (obj, text) {
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return obj.indexOf(text) > -1;
break;
case "object":
for (var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text))
return true;
};
break;
default:
return false;
};
return false;
};
angular.forEach(input, function (item) {
angular.forEach(parameters, function (params) {
if (search(item[params], filterby)) {
result.push(item);
};
});
});
return result;
};
}]);
Written by Janarthanan
Related protips
2 Responses
How about converting the filter to the Underscore
over 1 year ago
·
@satish1v: why ? angularJS has its own filter.
@Janarthanan: This is nice, but in case if you want to reuse this one , you better convert it to a filter and then embed it into html view. http://docs.angularjs.org/api/ng.filter:filter
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#