1

I am trying to load angular "select" with the following code

<select class="span11" ng-model="user.countryOfResidence" ng-options="c.option as c.value for c in countries" required>

Its loads the data into the select but the default selected value is empty.

my countries array is

$scope.countries = [{option:'TL', value:'TIMOR-LESTE'},
{option:'TK', value:'TOKELAU'},
{option:'TJ', value:'TAJIKISTAN'},
{option:'TH', value:'THAILAND'},
{option:'TG', value:'TOGO'},];

if i change 'TL' to 'TIMOR-LESTE', (same string for "option" and "value") it works fine. Can any one kindly tell me what is the problem with my code.

user object is

$scope.user = {

        countryOfResidence : $scope.countries[0].value

    };
1
  • 2
    Initialize $scope.user.countryOfResidence = $scope.countries[0].option because you are using options as values inside ng-option. Commented Sep 14, 2013 at 9:06

1 Answer 1

2

A select populated with ng-options will set the ng-model field to what is specified as the value, not the option

In the example you've given, you're setting user.countryOfResidence to countries[0].value, which in this case is 'TIMOR-LESTE', but the value key is 'TL', so it won't select it by default.

For better readability, I always like to structure my select options with 'label' and 'value' keys, like so:

// Controller

$scope.countries = [
  {value:'TL', label:'TIMOR-LESTE'},
  {value:'TK', label:'TOKELAU'},
  {value:'TJ', label:'TAJIKISTAN'},
  {value:'TH', label:'THAILAND'},
  {value:'TG', label:'TOGO'}
];

$scope.user = {
        countryOfResidence: $scope.countries[0].value
    };
};

// View

<select class="span11" ng-model="user.countryOfResidence" ng-options="c.value as c.label for c in countries" required=""></select>
Sign up to request clarification or add additional context in comments.

Comments

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.