How to conditionally deactivate an object in an array in Angular

advertisements

I have several select elements on the same page. Each select dropdown contains the same items. I would like to disable an item within the dropdown if it has already been selected in another select element. In other words, I don't want an item to be selected more than once across all of the select elements.

Any thoughts on how to accomplish this?

When I use the following code, nothing is disabled in the dropdown.

Code for controller:

var editProject = this;

editProject.addMore = function() {

  editProject.project.fruit.push({});
};

editProject.fruitids = [

  {code: 'GOODS', fruit: '1. Apple'},
  {code: 'GOODS', fruit: '2. Orange'},
  {code: 'GOODS', fruit: '3. Peach'},
];

HTML:

<div ng-repeat="item in editProject.project.fruits">

  <select ng-model="editProject.project.fruits[$index]"
ng-options="fruitid.class group by fruitid.code disable when (editProject.project.fruits.indexOf((fruitid)) !== -1)
for fruitid in editProject.fruitids track by fruitid.class">

    <option value="">--Select Class--</option>

  </select>

</div>

<button ng-click="editProject.addMore()" class="btn btn-default btn-xs" role="button">Add More Classes
</button>


You need to use a function as the expression for the disable parameter in the ng-options directive.

Please see working example1

HTML

 <div data-ng-repeat="item in items">
     <select data-ng-options="fruitId.fruit disable when isDisabled(fruitId) for fruitId in fruitIds" data-ng-model="items[$index]"></select>
  </div>

JS

$scope.isDisabled = function(fruitid) {
    return ($scope.items.indexOf((fruitid)) !== -1);
};

This will disable the option in all the select's including the the select where the option was selected. The option will now not be selected any more as it is disabled.

You need to exclude the current fruitId so it is still enabled in the selected select

Please see example2 where the current fruitId is excluded and the selected option is disabled in the other selects

We make sure that the index found is not the index of the current item.

HTML

<div data-ng-repeat="item in items">
    <select data-ng-options="fruitId.fruit disable when isDisabled(fruitId, item) for fruitId in fruitIds" data-ng-model="items[$index]"></select>
</div>

JS

$scope.isDisabled = function(fruitid, item) {
    return ($scope.items.indexOf((fruitid)) !== -1 && $scope.items.indexOf((fruitid)) != $scope.items.indexOf(item));
};