0

I for the life of me cannot figure out how to set both the labal and the value of a select using an array

I have an array of countries

$scope.countries =  [
    {abbr:"US", name:"United States"},
    {abbr:"CA", name:"Canada"},......
]

I want the select to generate as such

<select>
  <option value="US">United States</option>
  <option value="CA">Canada</option>
</select>

However the closest I have been able to achieve is

<select>
  <option value="1">United States</option>
  <option value="2">Canada</option>
</select>

I've achieved that using

<select class="form-control" ng-options="country.Name for country in countries" ng-model="selectedCountry">

How do I assign the label AND the value using ng-options?

2

2 Answers 2

1

Without testing I think it's just

ng-options="country.abbr as country.name for country in countries"
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I thought, but it produces a numbered value instead of my abbreviation value
Wow that's a little harsh - jsfiddle.net/devitate/uaxv70kc - it does work.
I'm sorry, you were correct. Apparently I was correct all along too. I was looking at the generated HTML and not at what was actually being stored in the model. Thanks
0

For exact structure, you need to do ng-repeat through your <option><option> ng-options will never set the value which which you want, It will always set 0,1,2,3 etc.

HTML

<select ng-model="selectedCountry">
    <option ng-repeat="country in countries" value="{{country.abbr}}" ng-bind="country.name"></option>
</select>

JSFiddle

Hope this could help you, Thanks.

1 Comment

@user1691808 if it does helpful then atleast do voteup..Thanks.

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.