I wrote a Angular filter to use filters based on properties that handles some specific properties differently.
Is there a way to improve or use some built-in Angular filter to avoid extra code?
Usage:
<div ng-repeat="item in items | myObjectFilter: { someProp: user.uid, pending: true }">
Code:
angular.module('app', []).filter('myObjectFilter', function () {
function _filter(source, search) {
if (!source) { return source; }
var result = [], defaultFilters;
//default filter setting
defaultFilters = {
pending: false,
refusedAt: null
};
search = angular.extend({}, defaultFilters, search);
angular.forEach(source, function (value, key) {
var isFiltered = true;
for (var x in search) {
if (value.hasOwnProperty(x)) {
var isEqual = false;
// handle specific properties or simply compare
switch (x) {
case 'someProp':
case 'someProp2':
isEqual = value[x].uid == search[x];
break;
default:
isEqual = value[x] == search[x];
break;
};
isFiltered = isFiltered && isEqual;
if (!isEqual) {
break; //exit loop if filter not passed
}
}
}
if (isFiltered) {
result.push(value); // add item to filterd result
}
});
return result;
};
return _filter;
});