3

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?

Nate
  • 7,606
  • 23
  • 72
  • 124
  • possible duplicate of [How to set value property in angularjs ng-options?](http://stackoverflow.com/questions/12139152/how-to-set-value-property-in-angularjs-ng-options) – Julien Jun 23 '14 at 09:14

1 Answers1

7

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.

Martin-Brennan
  • 917
  • 7
  • 19
guru
  • 4,002
  • 1
  • 28
  • 33