绑定ng-options数组中的一个属性

Bind one attribute of an array of ng-options

本文关键字:一个 属性 ng-options 数组 绑定      更新时间:2023-09-26

我有以下数组:

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

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

我试了以下方法(Jade)

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")

这可能吗?

您可以使用:

  <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 -将用于显示选中的项目。

请看这里的演示。

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