I'm trying to set the default item of a select box on load using angularjs.
I load both select boxes from 2 json's, so the second select box, named 'city' relies off the first select box 'country':
<label>Country:</label>
<select name="country" ng-model="form.country"
ng-options="c.n for c in countryList"
ng-change="countryChanged()" required></select>
<label>City:</label>
<select name="city" ng-model="form.city"
ng-options="c for c in cityList" required></select>
PLUNKER http://plnkr.co/edit/hKZLbMbwGfmaa8CtSy0H?p=preview
It loads the select boxes using $http.get
. It loads all well and good if i default it to the first option. But lets say, I want to specify a certain option to be selected on load, but I can only send it a particular value from the json, how would I do this? In the code below, the commented line is what I've tried, but all it does is load the correct city list, but leave the country select box unselected.
countries.json
[
{"c":"au","n":"Australia","g":"1"},
{"c":"fr","n":"France","g":"2"},
{"c":"ge","n":"Germany","g":"2"}
]
Controller:
$http.get('countries.json')
.success(function (data) {
$scope.countryList = data;
$scope.form.country = data[0];
// $scope.form.country.c = 'fr'; <<<--- *trying to set default*
$scope.countryChanged();
});
$scope.countryChanged = function() {
$http.get($scope.form.country.c + '-cities.json')
.success(function (data) {
$scope.cityList = data;
$scope.form.city = data[0];
});
}
Also, if there is a better way to achieve this, please post it.
Note: I can't join the json up. I split it because in the real world, there could be 100 countries each with 100 cities each and the json would be quite massive.