How to disable a <option> of select element when using AngularJS ng-options?

badaboum picture badaboum · Jan 8, 2014 · Viewed 57.9k times · Source

Is there a way to disable an option in a select element when we populate options with ng-options in AngularJS?

Like this: http://www.w3schools.com/tags/att_option_disabled.asp

You can do it by adding ng-disabled to each <option> tag, but is there a way to do it if we are using the ng-options directive in the select tag?

Answer

towr picture towr · Jan 8, 2014

One way to do this is, to forget using ng-options on the select element, and add the options in with ng-repeat, then you can add a ng-disabled check on each option.

http://jsfiddle.net/97LP2/

<div ng-app="myapp">
    <form ng-controller="ctrl">
        <select id="t1" ng-model="curval">
            <option ng-repeat="i in options" value="{{i}}" ng-disabled="disabled[i]">{{i}}</option>
        </select>
        <button ng-click="disabled[curval]=true">disable</button>
    </form>
</div>

a minimal controller for testing:

angular.module('myapp',[]).controller("ctrl", function($scope){
    $scope.options=['test1','test2','test3','test4','test5'];
    $scope.disabled={};
})