User970008
User970008

Reputation: 1155

Angular State Dropdown Bound to Country Select

I am trying to have a contextual state dropdown menu that is bound to the country so that only the relevant states display.

I have looked at these two answers for a solution to my implementation.

Angularjs trigger country state dependency

angularjs dependant dropdown option value

But I cannot get them to work and am missing something.

My preferred solution would use some existing ng filter, but I understand that only works on arrays and not objects

 <select ng-model="user.state" ng-options="state.name for state in states track by state.id | filter:state.countryid = user.country.id">

I tried converting the object to an array, but that did not seem to work.

I could create a custom filter, but I am hoping to avoid that.

 <select ng-model="user.state" ng-options="state.name for state in states track by state.id | customStateFilter:user.country.id">

It seems like there should be some way to get ng-options to work without modifying the data.

Is there an existing Angular filter that works on objects or a way to do conditional logic to filter out the objects dynamically?

Upvotes: 0

Views: 2436

Answers (1)

New Dev
New Dev

Reputation: 49590

You have a few issues here (in addition to a mismatch of state.countryid and country.id):

First, track by comes after the filter (or, in other words, filter comes right after the array, since it filters the array).

Second, you are right - the built-in filter filter only works on arrays, not objects. For objects, you'd need a custom filter.

And lastly, filter filter doesn't accept an expression to evaluate (filter:state.countryid = user.country.id, not to mention that this "expression" that you tried to provide doesn't compare ===, but assigns =). filter accepts as a parameter either a string - to match any property against, an Object specifying which property to match against which value, or a predicate function.

In your case, an object is what you need.

To put this thing together you get:

<select ng-model="selectedState"
        ng-options="state.name for state in states | filter: {countryid: user.country.id}:true track by state.id">
  <option value="">select state</option>
</select>

Upvotes: 1

Related Questions