Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering ng-options based on user selection

I have two select elements. The first one is used to select a country. The second one is used to select a state.

Every state is bound to a country.

States:

[{"code":"SC","name":"Santa Catarina","country":{"code":"BRA","name":"Brazil"}},    {"code":"RR","name":"Roraima","country":{"code":"BRA","name":"Brazil"}},{"code":"AL","name":"Alabama","country":{"code":"USA","name":"United States"}},{"code":"FL","name":"Florida","country":{"code":"USA","name":"United States"}}] 

Countries:

[{"code":"BRA","name":"Brasil"},{"code":"USA","name":"United States"}] 

HTML Content:

<select ng-model="userCountry" ng-options="country.name for country in countries track by country.name">

 <select ng-model="userState" ng-options="state.name for state in states track by state.name | filter: {state.country.code:userCountry.code}">

So, first, the user selects a country, which gets associated to "userCountry".

$scope.userCountry = new Object();

Now, the states select element should display only states associated with that country, but its currently loading all states. It's not working :(

I don't know If Im using the right syntax. Can anyone help me?

This is my filter:

| filter: {state.country.code:userCountry.code}

I tried many different variations without success.

Here is a Fiddle with my problem: http://jsfiddle.net/zrm7y80s/2/

It uses angular 1.2.23

Thank you!!

like image 889
Fabio K Avatar asked Mar 18 '23 22:03

Fabio K


1 Answers

Change your ng-options to this:

<select ng-model="userState" ng-options="state.name for state in ( states | filter: {country: { code: userCountry.code }}) track by state.name">

You want to run the filter before you do the track by, also you want to filter on the sub object, as state.country.code is invalid as an object key.

Updated Fiddle: http://jsfiddle.net/dw20jakt/

like image 152
Mathew Berg Avatar answered Apr 02 '23 12:04

Mathew Berg