简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM