2014-01-08 37 views
6

當我們在AngularJS中用ng-options填充options時,有沒有辦法在select元素中禁用option如何在使用AngularJS ng選項時禁用select元素的<option>?

像這樣:http://www.w3schools.com/tags/att_option_disabled.asp

你可以,如果我們使用的是ng-options指令在select標籤加入ng-disabled每個<option>標籤做到這一點,但有沒有辦法做到這一點?

+0

你是什麼意思的標籤,而不是標籤? –

+0

@IlanFrumer在選擇標籤,而不是在選項標籤,我已編輯我的帖子:) – badaboum

+0

是的,就這樣做。有用。 – towr

回答

13

一種方法是,在select元素上使用ng-options忘記,並與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> 

用於測試的最小控制器:

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

是的,我同意@towr,我在select標籤中看不到使用ng-options的解決方案。我喜歡這個實現,它很乾淨,易於理解。 – NicolasMoise

+2

它看起來像Angular 1.4的[ngOptions](https://code.angularjs.org/1.4.0-beta.5/docs/api/ng/directive/ngOptions)將允許禁用標籤禁用時.. 。' – Pakman

1

大概是這樣的

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

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

你確定嗎? @ luacassus的jsbin例子似乎工作,他使用相同的邏輯 – NicolasMoise

+0

@NicolasMoise是的,它工作絕對好,但我需要禁用該選項,而不是選擇?任何想法 ? – badaboum

+0

@NicolasMoise需要編輯 badaboum

2

您應該使用ng-disabled指令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> 

在這裏,你可以找到完整的例子來做到這一點http://jsbin.com/ihOYurO/1/

+0

很酷的例子我有我的應用程序中的相同,但我想要的是禁用選擇內的選項,而不是選擇? Capiché? – badaboum

+0

@badaboum yea在你的問題中根本不太清楚,寫出更好的問題,你會得到更好的答案。 – NicolasMoise

+0

@NicolasMoise我不是以英語爲母語的人!和平 – badaboum

7

角1.4 : 我們可以在ng-options中使用disable when,例如:

$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 

這個例子有遮陽分組的顏色,一些禁用:

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

我從the angular documentation得到這個代碼。

+2

這是最好的解決方案,但值得指出的一點是,它需要Angular 1.4或更高版本作爲@Fulup提及。 :) – Backer

+1

優秀的解決方案,就像一個魅力。 –

相關問題