简体   繁体   English

角度状态下拉列表绑定到国家/地区选择

[英]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触发国家/地区依存关系

angularjs dependant dropdown option value 与angularjs相关的下拉选项值

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 我的首选解决方案将使用一些现有的ng过滤器,但我知道这仅适用于数组而不适用于对象

 <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. 似乎应该有某种方法可以使ng-options正常工作而不修改数据。

Is there an existing Angular filter that works on objects or a way to do conditional logic to filter out the objects dynamically? 是否存在适用于对象的现有Angular过滤器,或者是否可以执行条件逻辑来动态过滤出对象?

You have a few issues here (in addition to a mismatch of state.countryid and country.id ): 您这里有几个问题(除了state.countryidcountry.id不匹配):

First , track by comes after the filter (or, in other words, filter comes right after the array, since it filters the array). 首先track by位于过滤器之后(或换句话说,filter紧接在数组之后,因为它过滤了数组)。

Second , you are right - the built-in filter filter only works on arrays, not objects. 其次 ,您是对的-内置的筛选filter筛选filter仅适用于数组,而不适用于对象。 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 = ). 最后filterfilter器不接受要计算的表达式( filter:state.countryid = user.country.id ,更不用说您尝试提供的“表达式”不比较=== ,而是分配= )。 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. filter接受一个string作为参数,以匹配任何属性,一个Object指定一个属性来匹配哪个值,或者一个谓词函数。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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