Angularjs filter on nested property
-
21-12-2019 - |
Question
I have an array of the following json object:
{
fooBar:{
Id: 2
Foo: {
Id: 4
IsNew: false
}
Bar: {
Id: 1
IsNew: false
}
}
}
and I want to filter on the fooBar.Foo.Id
, so based on this answer I was expecting the following to work:
<div data-ng-repeat="fooBar in fooBars | filter:{Foo:{Id : 4}}:true">
But this does not return me anything.
I can do the following however to filter on fooBar.Id and that works fine:
<div data-ng-repeat="fooBar in fooBars | filter:{Id : 2}:true">
Should I be writing custom filters for this kind of one level down child property matching? Or is there anything obvious that I am doing wrong?
Solution
Based on this answer, I solved the problem by creating a custom filter:
app.filter('fooBarFilter', [function () {
return function (foobars, fooId) {
var result = {};
angular.forEach(foobars, function (foobar, key) {
if (foobar.foo.Id === fooId) {
result[key] = foobar;
}
});
return result;
};
}]);
and used it to filter the collection in the HTML:
<div data-ng-repeat="(key, fooBar) in fooBars | fooBarFilter : 4">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow