使用AngularJS ng-options时如何禁用select元素的<option>?

bad*_*oum 8 angularjs angularjs-directive ng-options

有没有一种方法来禁用optionselect,当我们填充元素options与AngularJS NG选项?

像这样:http://www.w3schools.com/tags/att_option_disabled.asp

您可以通过添加ng-disabled到每个<option>标记来实现,但如果我们ng-optionsselect标记中使用该指令,是否有办法执行此操作?

tow*_*owr 13

一种方法是,忘记ng-optionsselect元素上使用,并添加选项ng-repeat,然后你可以添加一个ng-disabled检查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>
Run Code Online (Sandbox Code Playgroud)

用于测试的最小控制器:

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

  • 看起来像Angular 1.4的[ngOptions](https://code.angularjs.org/1.4.0-beta.5/docs/api/ng/directive/ngOptions)将禁用`标签禁用... ` (2认同)

Nic*_*lle 11

来自Angular 1.4:我们可以disable when在ng-options中使用,例如:

 $scope.colors = [
  {name:'black', shade:'dark'},
  {name:'white', shade:'light', notAnOption: true},
  {name:'red', shade:'dark'},
  {name:'blue', shade:'dark', notAnOption: true},
  {name:'yellow', shade:'light', notAnOption: false}
];
$scope.myColor = $scope.colors[2]; // red
Run Code Online (Sandbox Code Playgroud)

此示例具有按阴影分组的颜色,其中一些已禁用:

<select ng-model="myColor" ng-options="color.name group by color.shade disable when color.notAnOption for color in colors"></select>
Run Code Online (Sandbox Code Playgroud)

我从角度文档中获取了此代码.

  • 这是最好的解决方案,但有一点值得指出的是,它需要Angular 1.4或更高版本,因为@Fulup提到了.:) (2认同)