I have a JS array of objects.
$scope.users = [{
"name": "alice",
"city": "london",
"wards": [{
"id": 1,
"number": 24
},
{
"id": 2,
"number": 25
},
{
"id": 3,
"number": 26
}
]
},
{
"name": "bob",
"city": "london",
"wards": [{
"id": 1,
"number": 24
},
{
"id": 2,
"number": 25
},
{
"id": 4,
"number": 27
}
]
}
]
I have a ng-repeat="user in users | filter: searchUser
Here searchUser
can contain name, city and ward number.
Now the search is working fine for name and city but not for the sub array of objects wards to search for ward number.
Is there an angularJS way with which I could achieve this?
No. You need to write your own custom filter.
Here is a sample jsfiddle, tested with input search
alice, bob, london, 26, 27
If you want exact match, then change -1 to 0
app.filter('myFilter', function(){
return function(users, search){
if(!search) return users;
if(!users || !users.length) return users;
searchInLower = search.toString().toLowerCase();
users = users.filter(function(user){
matches = false;
if(user.name){
usernameInLower = user.name.toString().toLowerCase();
matches = matches || usernameInLower.indexOf(searchInLower) !== -1;
}
if(user.city){
cityInLower = user.city.toString().toLowerCase();
matches = matches || cityInLower.indexOf(searchInLower) !== -1;
}
if(user.wards && user.wards.length && !matches){
for(var i = 0; i < user.wards.length; i++){
ward = user.wards[i];
for(var key in ward){
objectKeyValueInLower = ward[key].toString().toLowerCase();
matches = matches || objectKeyValueInLower.indexOf(searchInLower) !== -1;
}
}
}
return matches
});
return users;
}
})