Created
May 8, 2015 17:54
-
-
Save TrevorJTClarke/10a4d51f10eeb16ea8e5 to your computer and use it in GitHub Desktop.
Easier setup for deep object based filtering on an array in angularjs. Use: ng-repeat="item in someArray | objectFilter:filterReqObject"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I wanted to be able to simply change an object with key/search values, so that any array item keys that match also check for those search values | |
// The returned data, is only data that meets all requirements inside of the filterObject | |
// | |
// Example filterObject:{ | |
// names: "Trevor", | |
// countries: "USA" | |
// } | |
// Example Array: [{ | |
// title: "People in USA" | |
// names: ["Trevor", "Steve"] | |
// countries: ["USA"] | |
// },{ | |
// title: "People in the world" | |
// names: ["John", "Steve"] | |
// countries: ["EU","USA"] | |
// }] | |
App.filter('objectFilter', [function($filter) { | |
return function(inputArray, filterObject){ | |
if(!angular.isDefined(filterObject) || filterObject === ''){ | |
return inputArray; | |
} | |
// assume the item has all filters until proven false | |
function hasAllFilters ( item ){ | |
for(var meta in filterObject){ | |
if(item[meta].indexOf(filterObject[meta]) === -1){ | |
return false; | |
} | |
} | |
return true; | |
} | |
// setup only data that meets all requirements | |
var data = []; | |
angular.forEach(inputArray, function(item){ | |
if(hasAllFilters(item)){ | |
data.push(item); | |
} | |
}); | |
return data; | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
H2o