【问题标题】:Bind one attribute of an array of ng-options绑定一组 ng-options 的一个属性
【发布时间】:2014-08-13 06:14:30
【问题描述】:

我有以下数组:

[{code: "AF", name: "Afghanistan"}, {code: "ZA", name: "South Africa"}, {code: "AL", name: "Albania"}]

我有一个选择,并希望仅将我的 ng-model 绑定到所选对象的代码属性上,而不是整个对象。但另一方面,我希望我的选择只显示名称(而不是代码)。另外,我希望如果我将我的 ng-model 设置为代码,它会在选择中预先选择名称。

我尝试了以下(翡翠)

select(ng-model='myCountry', ng-options='country.name for country in countries track by country.name')

这里我的 ng-model 获取整个对象 (myCountry = {code: "AF", name: "Afghanistan"}) 而不仅仅是代码 (myCountry = "AF")

有可能吗?

【问题讨论】:

标签: javascript angularjs ng-options


【解决方案1】:

你可以使用:

  <div>
    <select ng-model="country" ng-options="country.code as country.name for country in countries"></select>
    Selected country (ng-model): {{country}}
  </div>

country.code - 将用作ng-model 属性。

country.name - 将用于在选择中显示项目。

See the demo here.

如果您想将选择选项设置为预选值,只需使用country 模型来提供该值。

【讨论】:

  • 谢谢...但我忘了说选择需要按数组索引排序。可以轻松添加吗?
  • 第二句和第三句是辉煌的冠军。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多