简体   繁体   中英

Binding select with ng-options using an array of labels and values

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?

未经测试,我认为这只是

ng-options="country.abbr as country.name for country in countries"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM