简体   繁体   中英

How to make already selected option not display in another select option dropdown JAVASCRIPT/ANGULARJs

How to make a select option not disappear when selected if filtered out and not be displayed on other select dropdowns. For example if i have some array of objects, and i make

<select ng-options = "here we go through each object "></select>

My idea is to make filter function that would not display any item that's in the array i'm filling if I selected this item before. So that would be my array of items that should be unavailable in another dropdowns. Is there some example way how can i accomplish that? I have an idea that my filter would look something like this:

  for(var i=0;i<$scope.removedIds.length;i++){
    if(tab.tabID===$scope.removedIds[i].tabID)
      return false;
  }
  return tab;

and this would be used in ng-options for ex: ng-options="tab.ID as tab.name for tab in tables | filter: " and in my function ng-change i would be adding to $scope.removedIds next values that should not be available in next select dropdowns. But I think it would not work because values would be filter out in different select dropdowns.

Example

I guess that you have three dropdowns with same datasource, a simple solution would look like:

<div>
    <select ng-model="selectedItem1" ng-options="item1 for item1 in options1"></select>
    <select ng-model="selectedItem2" ng-options="item2 for item2 in options2"></select>
    <select ng-model="selectedItem3" ng-options="item3 for item3 in options3"></select>
</div>

In the corresponding controller, and using angularjs watchers, add these lines:

$scope.options1 = ["opt1","opt2","opt3"];
$scope.options2 = angular.copy($scope.options1);
$scope.options3 = angular.copy($scope.options1);

$scope.$watch("selectedItem1", function(nv, ov) {
    if (nv != ov) {
        $scope.options2.splice($scope.options2.indexOf(nv),1);
        $scope.options3.splice($scope.options3.indexOf(nv),1);
    }
});
$scope.$watch("selectedItem2", function(nv, ov) {
    if (nv != ov) {
        $scope.options1.splice($scope.options1.indexOf(nv),1);
        $scope.options3.splice($scope.options3.indexOf(nv),1);
    }
});
$scope.$watch("selectedItem3", function(nv, ov) {
    if (nv != ov) {
        $scope.options1.splice($scope.options1.indexOf(nv),1);
        $scope.options2.splice($scope.options2.indexOf(nv),1);
    }
});

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