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?

mrb398
  • 1,277
  • 4
  • 24
  • 32
  • 1
    https://docs.angularjs.org/api/ng/directive/ngOptions. The angular docs tell you how to do this. – ribsies Feb 27 '15 at 20:46
  • This already has been answered by http://stackoverflow.com/questions/12139152/how-to-set-value-property-in-angularjs-ng-options – gerl Feb 27 '15 at 21:02

2 Answers2

1

Without testing I think it's just

ng-options="country.abbr as country.name for country in countries"
Dylan
  • 4,703
  • 1
  • 20
  • 23
  • This is what I thought, but it produces a numbered value instead of my abbreviation value – mrb398 Feb 27 '15 at 20:58
  • 1
    Wow that's a little harsh - http://jsfiddle.net/devitate/uaxv70kc/ - it does work. – Dylan Feb 27 '15 at 21:18
  • 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 – mrb398 Feb 27 '15 at 21:34
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.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299