Jannie Jannie - 1 year ago 65
AngularJS Question

How can I set the default option in select box when an item was removed from the list - angularjs

I have an angularjs controller and html view which shows a list of employee names and if they are a supervisor or not and lastly a list of supervisors to choose from. There will always be at least one default supervisor in the list, which in this case is Sally.

The supervisor dropdown can change according the "Is Supervisor?" selection. If the employee is set to be a supervisor their name will appear in the dropdown. If the employee is set not to be a supervisor, their name will be dropped from the supervisor list and subsequently the dropdown also.

In this example we have the default supervisor, Sally and one other employee, Tom, is also marked as a supervisor.

Lets change the supervisor of Harry to that of Tom.

Now if I change Tom to not be a supervisor anymore, I expect the supervisor dropdown for Harry to be changed to the default supervisor, Sally. But instead, a "blank" option appears in the drop down next to Harry instead.

And that is the problem, does anyone have any suggestion on how to fix this?

You can find the code at https://jsfiddle.net/w7gy6hn3/

<select ng-init="defaultSupervisorId = responsiblePerson.id"
ng-options="supervisor.id as (supervisor.name + ' ' + supervisor.id) for supervisor in supervisorList">

Answer Source

here is the updated fiddle https://jsfiddle.net/55uk6m8L/ just add the below extra code to your controller

$scope.updateDropDown = function(employee) {

 for(var i=0;i<$scope.employees.length;i++)
   if($scope.employees[i] != employee && $scope.employees[i].defaultSupervisorId == employee.id )

     $scope.employees[i].defaultSupervisorId = $scope.supervisorList[0].id;


call this function in your in $scope.updateSupervisorList functions inside else block after splice method


and also in html , i change the these lines

<select ng-init="employeeInfo.defaultSupervisorId = responsiblePerson.id"
                            ng-options="supervisor.id as (supervisor.name + ' ' + supervisor.id) for supervisor in supervisorList">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download