phantom phantom - 4 months ago 39
AngularJS Question

ng-init for drop down not working from api call

I am making a call to an API and using this response to populate a select drop down list. I am trying to prepopulate the select drop down box with 'Please choose a country', however as the countries are being returned from an api call the following isn't working as I guess

$scope.countries.select
is not defined at this stage.

HTML

<select ng-init="countries.select" ng-model="country" ng-change="getRoles(country)" ng-options="key as value for (key , value) in countries"></select>


the countries object returned from the api call looks like this:

$scope.countries = {
AU:"Australia",
BE:"Belgium",
US:"United States"
}


which I then push the following into

$scope.countries.select = "Please select a country";


As
countries.select
is not defined as the api response still needs to be returned which I believe is the reason that this is not working.

Answer

You are not initialising the value of countries properly. Since js doesnot know what is countries then you can not assign countries.select since countries is undefined. First initialise countries to empty object = {}.

However if you just have to display the default selected option of the list to read "Please choose a country" you can do this.

<select ng-model="country" ng-change="getRoles(country)" ng-options="key as value for (key , value) in countries">
<option value="">Please choose a country</option>
</select>