John Smith
John Smith

Reputation: 1105

Angularjs ng-repeat remove selected option from multiple select boxes

Using ng-repeat am loading multiple select dropdown elements and each dropdown has the same set of values loaded. Once the user selects an option from the select box; The selected option shouldn't appear in other select boxes(options).

Example: If the user selects Option A from select: 1; then in select: 2 or any other select: N the Option A shouldn't appear and vice-versa.

Plunker: https://plnkr.co/edit/yCFIanCXPece49dk?open=lib%2Fscript.js&deferRun=1&preview

Code:

 <option ng-repeat="option in data.availableOptions | filter:arrayFilter(select.selectedOption,$index)" value="{{option.id}}">

   $scope.arrayFilter = function(selectionArray, position) {
    return function(item, index) {
      return selectionArray.indexOf(item.id) == -1 || item.id == selectionArray[position];
    }
  }

Upvotes: 1

Views: 903

Answers (1)

Moshezauros
Moshezauros

Reputation: 2593

You can get the options to the nested ng-repeat with a function, and then filter out options which are not the current one and are selected:

html:

<select name="repeatSelect{{$index}}" id="repeatSelect{{$index}}" ng-model="select.selectedOption">
  <option
    ng-repeat="option in getAvailableOptions(select.selectedOption)"
    value="{{option.id}}"
  >
    {{option.name}}
  </option>
</select>

controller:

$scope.getAvailableOptions = function(current) {
  return this.data.availableOptions.filter((o) => o.id === current || !this.data.availableSelect.some(s => s.selectedOption === o.id));
};

and here is a forked plunker

Upvotes: 0

Related Questions