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

nco*_*hen 3 javascript angularjs ng-options

我有以下数组:

[{code: "AF", name: "Afghanistan"}, {code: "ZA", name: "South Africa"}, {code: "AL", name: "Albania"}]
Run Code Online (Sandbox Code Playgroud)

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

我试过以下(玉)

select(ng-model='myCountry', ng-options='country.name for country in countries track by country.name')
Run Code Online (Sandbox Code Playgroud)

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

有可能吗?

gur*_*uru 7

您可以使用:

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

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

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

请在此处查看演示.

如果要将select选项设置为预选值,只需使用country模型提供值即可.