I need to populate html select options with all states in USA. It would be helpful if I can see an example. Do I need to have all the states defined in a scope variable?
Thanks!
Not at all, No need to define all states individually in scope. you can make simple use of $watch service in angular js.
please refer the jsfiddle link here:
states and cities can be taken inside an array of objects and data-ng-options is used to show the options which will be loaded from controller. $watch will watch on change of state and load the city accordingly.
function Controller($scope) {
var states = [{
"Name": "karnataka",
"cities": [{
"Name": "bangalore"
}, {
"Name": "mangalore"
}, {
"Name": "mysore"
}]
}, {
"Name": "maharashtra",
"cities": [{
"Name": "Mumbai"
}, {
"Name": "pune"
}, {
"Name": "nagpur"
}]
}];
$scope.groups = states;
$scope.currentGroup = states[0];
$scope.currentItems = $scope.currentGroup.cities;
$scope.currentItem = $scope.currentItems[0];
$scope.$watch('currentGroup', function () {
$scope.currentItems = $scope.currentGroup.cities;
$scope.currentItem = $scope.currentGroup.cities[0];
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app ng-controller="Controller">
<div class="span4">
<label for="cboGroup">States</label>
<select data-ng-model="currentGroup" data-ng-options="group.Name for group in groups"></select>
</div>
<div class="span4">
<label for="cboItem">Cities</label>
<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentItems"></select>
</div>
<div>
Selected city : {{currentItem.Name}}
<div>
</section>
yes the best way would be store it in an array of objects as a scope variable and then use it in your template.
Something like this....
let's say $scope.allState[] is an array of objects of all states in USA.
then in your templates try it as....
<select type="text" name="name" id="name"
data-ng-model="formData.state"
ng-options="state for state in allState"
required >
<option value="">Select</option>
</select>
ng-optionsfor a select