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

柔情痞子 提交于 2019-12-18 05:52:27

问题


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?


回答1:


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={};
})



回答2:


From Angular 1.4 : We can use disable when in ng-options, for example:

 $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

This example have colors grouped by shade, with some disabled:

<select ng-model="myColor" ng-options="color.name group by color.shade disable when color.notAnOption for color in colors"></select>

I got this code from the angular documentation.




回答3:


You should use ng-disabled directive http://docs.angularjs.org/api/ng.directive:ngDisabled.

<body ng-app="myApp">

  <div ng-controller="myCtrl">
    <form class="form-inline">
      <div class="form-group">
        <select class="form-control" ng-disabled="disableSelect">
          <option val="one">First</option>
          <option val="two">Second</option>
        </select>
      </div>

      <button class="btn btn-default" ng-click="disableSelect = !disableSelect">
        Disable select
      </button>
    </form>
  </div>

</body>

Here you could find the complete example http://jsbin.com/ihOYurO/1/




回答4:


Solve with version 1.4 https://docs.angularjs.org/api/ng/directive/ngOptions [double check you look for v1.4 documentation]




回答5:


Probably something like this

<button ng-click='disableSelect=true'></button>

<select ng-disabled='disableSelect'></select>


来源:https://stackoverflow.com/questions/21002616/how-to-disable-a-option-of-select-element-when-using-angularjs-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!