Search code examples
angularjsangularjs-ng-optionsangularjs-ng-disabled

Disable ng-options value dynamically


I want to disable select option which is in loop. So far i have implemented in following link. Its working way I wanted but i have made code very long. Is there any other way to implement.

Code Link

<div ng-controller="OptionsController">
<button value="add" ng-click="add()">
add
</button>
<div ng-repeat="val in v">
    <select ng-model="val.myColor" ng-change="call(c.name)">
        <option ng-repeat="c in colors" ng-disabled="c.shade=='dark'" value="{{c.name}}">
            {{c.name}}
        </option>
    </select>

</div>

</div>

Solution

  • ng-options with disabled rows has some details on how to use ng-options with disabled options.

    Based on your current use of the ng-repeat: http://jsfiddle.net/rhz8hxL5/1/

    <div ng-controller="OptionsController">
      <button value="add" ng-click="add()">
        add
      </button>
      <div ng-repeat="val in v">
        <select ng-model="val.myColor" ng-change="call()">
          <option ng-repeat="c in colors" ng-disabled="isDisabled(c)" value="{{c}}">
            {{c}}
          </option>
        </select>
      </div>
    </div>
    

    JS - I simplified it a bit for clarity in demonstration

    angular.module('myApp', [])
    
    function OptionsController($scope, $timeout) {
      $scope.v = [{
        myColor: 0
      }];
    
      $scope.inUse = [];
      $scope.isDisabled = function(name) {
        return $scope.inUse.indexOf(name) !== -1;
      }
    
      $scope.colors = ['black', 'white', 'red', 'blue', 'yellow'];
    
      $scope.add = function() {
            $scope.v.push({});
      }
    
      $scope.call = function() {
        $scope.inUse = [];
    
        for(var i=0; i<$scope.v.length; i++) {
          var val = $scope.v[i];
    
          $scope.inUse.push(val.myColor);
        }
      }
    }
    

    In English:

    The $scope.inUse array is maintaining a list of currently selected values. When you change a dropdown value it invokes the call function. That function empties the $scope.inUse array and re-populates it with the currently selected values.

    The $scope.isDisabled function returns a boolean on the basis that "If it has an index it is in use and thus disabled"