model view controller - how to populate html select element options in angularjs? -
i need populate html select options states in usa. helpful if can see example. need have states defined in scope variable?
thanks!
not @ all, no need define states individually in scope. can make simple use of $watch service in angular js.
please refer jsfiddle link here:
states , cities can taken inside array of objects , data-ng-options used show options loaded controller. $watch watch on change of state , load 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 group in groups"></select> </div> <div class="span4"> <label for="cboitem">cities</label> <select data-ng-model="currentitem" data-ng-options="item.name item in currentitems"></select> </div> <div> selected city : {{currentitem.name}} <div> </section>
Comments
Post a Comment