简体   繁体   中英

using ng-options with angular to display select option with key and value and setting a default value

I have the following json:

[
    {"country": "United States", "code": "US"},
    {"country": "Canada", "code": "CA"},
    {"country": "Mexico", "code": "MX"}
 ]

In my view i have

 <select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="country.country as country.country for country in countries" ng-change="onCountryChange()" required></select>

i am able to set a default country in my controller but the only problem is the drop down looks like this

 <option value="0" selected="selected">United States</option>
 <option value="1">Canada</option>
 <option value="2">Mexico</option>

when i add track by country.code in my ng-options i get the select list correctly with values set correctly

 <option value="?" selected="selected"></option>
 <option value="US">United States</option> 
 <option value="CA">Canada</option>
 <option value="MX">Mexico</option>

but i am unable to set a default from my controller

 $scope.selectedCountry = "Canada";

or

    $scope.selectedCountry = "CA";

Does anyone know how i can fix this issue.

With track by expression, you can omit any other properties and set the default value like this:

$scope.selectedCountry = { code: "CA" };

Hope this helps.

EDIT: If you would like the value of $scope.selectedCountry to be just a string (ie 'US', 'CA, or 'MX'), there is no need to use track by , you could use an ng-options like this:

<select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="country.code as country.country for country in countries" ng-change="onCountryChange()" required></select>

Example Plunker: http://plnkr.co/edit/QBRoV09sAlufSffpPPpJ?p=preview

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