1
votes

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 - charlietfl

1 Answers

2
votes

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>