简体   繁体   中英

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-model="defaultSupervisorId" 
    ng-options="supervisor.id as (supervisor.name + ' ' + supervisor.id) for supervisor in supervisorList">
</select>

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

 $scope.updateDropDown(employee);

and also in html , i change the these lines

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM