Reputation: 2254
I understand to filter an object in ng-repeat you do:
<div ng-repeat = "name in names | filter: {name: 'David'}"></div>
however, what if I want to show 'David' and 'Andrew'
I have tried
<div ng-repeat = "foo in fooObj | filter: {name: 'David' && 'Andrew'}"></div>
and
<div ng-repeat = "foo in fooObj | filter: {name: 'David'} | filter: {name: 'Andrew'}"></div>
Both don't work the way I want to. Is this a case where I need a custom filter or is there something in the API i'm not seeing?
Upvotes: 0
Views: 5763
Reputation: 133
In case anyone is still having trouble with these types of filters. I know the OP didn't need a complex solution as this one. However, anyone dealing with multi-dimensional arrays or objects won't be able to use the accepted answer.
This is my solution. It took me a while to combine a few different strategies to get my desired filter. This same strategy can be applied to many different scenarios, with various data models.
data model example
items: {
item: {
type: { 'foo' }
},
item: {
type: { 'bar' }
},
item: {
type: { 'foo' }
},
item: {
type: { 'blah' }
}
}
My ng-repeat
data-ng-repeat="item in items | filter:searchText | filterByType:['foo', 'meh']"
And finally this is my filter function. I created a module level filter.
angular.module('items')
.filter('filterByType', function () {
return function (items, types) {
var filtered = [];
filtered = items.filter(function (item) {
return types.indexOf(item.type) !== -1;
});
return filtered;
};
});
Upvotes: 0
Reputation: 2254
html
<div ng-repeat = "name in names | filter: nameFilter "></div>
controller
$scope.nameFilter = function(name){
if (object.name === 'David' || object.name === 'Andrew'){
return object.name;
} else {
return;
}
};
Obviously @Materik's solution is re-usable and I would actually put that in my filter module for later use! Thanks again
Upvotes: 1
Reputation: 4248
Try this:
html
<div ng-controller="NameController">
<div ng-repeat="name in names | filter: 'David,Andrew': compare">
{{name}}
</div>
</div>
js
app.controller(NameController, function($scope) {
$scope.names = [
'David',
'Andrew',
'Charles',
...
];
$scope.compare = function(name, expected) {
var expectedNames = expected.split(',');
return expectedNames.indexOf(name) > -1;
});
});
Upvotes: 3