Search code examples
angularjsng-options

dependent ng-model in angularjs


I am having two select controls. based on one select control second select control should be populated just like on country select state will fill in second select control.

my code is like -

<select ng-model="parentModel" id="ddlState">
<option value="mp"> mp </option>
<option value="mh"> mh </option>
</select>

<select ng-model="childModel" id="ddlcity" ng-options = "a as a for a in $scope.coll[parentModel]">
</select>

and script is -

<script>

    var arr=  new Array();
    arr["mp"] = ['map1','map2'];
    arr["mh"] = ['mh11','mh2'];


    myapp = angular.module("myapp", []);

    myapp.controller("MyController", function ($scope) {

        $scope.parentModel = "mh";
        //$scope.childModel="pune";
        $scope.coll=arr;
    });
</script>

Thanks in advance...


Solution

  • You have the right idea - a couple changes though:

    JavaScript doesnt have associative arrays, so use an object:

    $scope.arr = {};
    $scope.arr.mp = ["map1", "map2"];
    $scope.arr.mh = ["mh11", "mh2"];
    

    No need to reference $scope in your ng-options

    ng-options = "a as a for a in arr[parentModel]"
    

    Not sure what $scope.coll was meant to be...but it's not needed to make a dependent select in your case.