Yeak
Yeak

Reputation: 2538

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.

Upvotes: 1

Views: 1580

Answers (1)

runTarm
runTarm

Reputation: 11547

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 (i.e. '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

Upvotes: 2

Related Questions