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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks...but I forgot to say that the selection needs to be sorted by array index. Can you add that easily?
Those second and third sentences are brilliant champ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.