1

We create our drop-downs dynamically and like that we put them on the page, very generic. Currently, I need to have 2 drop-downs dependent on each other, employee - role. Because the drop-downs are dynamic, there is no relationship between them.

Using AngularJS, what would be a good way to create cascading between the 2 drop-downs? I thought of the onChange event for the drop down, but how can I "inject" this event to the drop down after the dom has completing its cycle?

1
  • use ng-change to update the array used for the second dropdown Commented Feb 25, 2016 at 19:34

1 Answer 1

2

This JSFiddle should help. I believe it will demonstrate what you're after. Note that in the $scope.change_role function, you can alter the values of the lists as necessary.

var myApp = angular.module('myApp', []);

myApp.controller('myController', function($scope) {
  $scope.msg = "hello";

  $scope.role_list = [{
    "role_id": 1,
    "role_name": "admin"
  }, {
    "role_id": 2,
    "role_name": "everyone"
  }];

  $scope.action_list = [{
    "action_id": 1,
    "action_name": "read"
  }, {
    "action_id": 2,
    "action_name": "write"
  }];

  // When the role is changed, assign the default id of the preferred action
  $scope.change_role = function(role_id) {
    if (role_id == 1) {
      $scope.record.action_id = 2;
    } else {
      $scope.record.action_id = 1;
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
  <select ng-change="change_role(record.role_id)" ng-model="record.role_id" ng-options="obj.role_id as obj.role_name for obj in role_list">
    <option ng-show="record.role_id == 0" value="">-- Choose Role --
    </option>
  </select>
  <select ng-model="record.action_id" ng-options="obj.action_id as obj.action_name for obj in action_list">
    <option ng-show="record.action_id == 0" value="">-- Choose Action --
    </option>
  </select>
  <br>
  <br>Role ID:{{record.role_id}}
  <br>Action ID:{{record.action_id}}
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Adding another JSFiddle to show an example where the user's choice of the first select dropdown dynamically adds options in the second select.
Was this a satisfactory answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.