0

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?

2

1 Answer 1

1

No. You need to write your own custom filter.

Here is a sample jsfiddle, tested with input search

alice, bob, london, 26, 27

http://jsfiddle.net/1dura7m3/

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;
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.