Nate
Nate

Reputation: 7876

Bind one attribute of an array of ng-options

I have the following array:

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

I have a select and would like to bind my ng-model only on the code attribute of the selected object and not the whole object. But on the other hand, I would like my select to display only the name (and not the code). In addition, I would like that if I set my ng-model to a code, it will pre-select the name in the selection.

I tried the following (Jade)

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

Here my ng-model gets the whole object (myCountry = {code: "AF", name: "Afghanistan"}) and not just the code (myCountry = "AF")

Is it possible to do that?

Upvotes: 3

Views: 841

Answers (1)

guru
guru

Reputation: 4022

You can use:

  <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 - will be used as the ng-model attribute.

country.name - will be used to display the item in select.

See the demo here.

And if you want to set the select option to a pre-selected value just use the country model to supply the value.

Upvotes: 7

Related Questions