Search code examples
javascriptangularjsangular-filters

How to filter by object's property in AngularJS?


I have two array of objects as shown below:

$scope.countries = [
        {'id' : 1, 'country_name':'India'},
        {'id' : 10, 'country_name':'Australia'},
        {'id' : 2, 'country_name':'England'}
    ];
$scope.states = [
        {'state_id' : 1, 'state_name':'Delhi', 'country_id':{'id':1 ,'country_name':'India'}},
        {'state_id' : 5, 'state_name':'London', 'country_id':{'id':2 ,'country_name':'England'}},
        {'state_id' : 2, 'state_name':'Victoria', 'country_id':{'id':10 ,'country_name':'Australia'}}
    ];

I'm trying to filter the states based on the id inside the country_id object as shown below:

<select ng-model="sellerCountry" ng-options="item.id as item.country_name for item in countries" required>
    <option value="">Select Country</option>
</select>   

<select ng-model="sellerState" ng-options="item.id as item.state_name for item in states | filter : {country_id: { id : sellerCountry}, }" ng-disabled="!sellerCountry">
    <option value="">Select State</option>
</select>

Here, when i select India ( where id = 1) from the first select box, i should only get Delhi to be displayed in second select, but its displaying Delhi (country_id.id = 1) and Victoria( country_id.id = 10 )

Need help to sort out this. Thanks in advance.


Solution

  • By default filters do contains search, you should make that filter to do strict comparison, by passing 3rd parameter to true to filter.

     ng-options="item.id as item.state_name for item in states
                   | filter : {country_id: { id : sellerCountry} }: true"
    

    Demo Plunker