Search code examples
javascriptangularjsangular-ngmodelng-optionsangularjs-ng-options

angularjs - Dropdown depends on other dropdown not working when id/name combo


I've been using the solution provided by @Brocco here: Dropdown depends on other dropdown - angularjs

I've noticed that when you use an ID/Name combo in the object for use by Angular it automatically fails. I've tested this with the provided JSFiddle AngularJS version as well as the latest AngularJS version and in both instances it fails.

JSFiddle:

http://jsfiddle.net/h8uoy9xr/ (updated fiddle link)

HTML:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<div ng-app>
    <div ng-controller="MyCntrl">
        <select ng-model="server" ng-options="server.id as server.name for server in servers"></select>
        <!-- server.name for server in servers (This works a treat, but not the other way) -->
        <select ng-model="version" ng-options="version.id as version.name for version in server.version"></select>
    </div>
</div>

JS:

function MyCntrl($scope) {


    $scope.servers = 
       [
           {
               "id": 1,
               "name": "server1",
               "version":
               [
                   {id:1,name: "10.x"}
               ]
           },
           {
               "id": 2,
               "name": "server2",
               "version":
               [
                   {id:2,name:"1"}, {id:3,name:"2"}
               ]
           }
       ];


}

Solution

  • If you display the value of the server you will find out that it gets only the id, not the whole object assigned.

    Change

    ng-options="server.id as server.name for server in servers"
    

    to

    ng-options="server as server.name for server in servers"
    

    in order to get it working.

    The value before the as keyword is saved to model. The value after is used as a label in the dropdown.