kishore kishore - 2 months ago 12
AngularJS Question

Use of ng-option

Here i have created an array with countries, when i select a particular country then their list of states should be displayed in another select tab. How can i do that




<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selectedName" ng-options="item for item in names">
</select>
{{selectedName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["India", "US", "UK"];
});
</script>


</body>
</html>

Answer

I'm going to give you a hint in the right direction, their are a ton of ways to do this and this is nowhere near a real world example.

<div ng-app="myApp" ng-controller="myCtrl">

    <select ng-model="selectedName" ng-options="item for item in names" ng-change="countrySelected()"></select>
    {{selectedName}}
    <select ng-model="selectedState" ng-options="item for item in states"></select>
    {{selectedState}}

</div>

<script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope) {
                $scope.names = ["India", "US", "UK"];
                $scope.states = [];

                $scope.countrySelected = function () {
                    if ($scope.selectedName == "India") {
                        $scope.states = ["Some", "State"];
                    }
                }
            });
</script>

Normally you would have a structured data coming from your back-end, for example:

[{ country:"US", states: ["One", "Two"]}]

Once a country is selected, the states should be used in the other select box. Also some ID's would come from your backend, so you can send the selected countryID and stateID to the server once completed.

Comments