@Lod Angularが指摘したように、1.4.0-beta.5 でこれのサポートが追加されました。
angular js >= 1.4.0-beta.5 の場合。
<select ng-options="c.name disable when c.shade == 'dark'
group by c.shade for c in colors">
angular js < 1.4.0-beta.5については、以下のソリューションを参照してください。
@lucumaによって与えられたものに似ていますが、jQuery の依存関係はありません。
これをチェックしてくださいhttp://jsfiddle.net/dZDLg/46/
コントローラ
<div ng-controller="OptionsController">
<select ng-model="selectedport"
ng-options="p.name as p.name for p in ports"
options-disabled="p.isinuse for p in ports"></select>
<input ng-model="selectedport">
</div>
指令
angular.module('myApp', [])
.directive('optionsDisabled', function($parse) {
var disableOptions = function(scope, attr, element, data,
fnDisableIfTrue) {
// refresh the disabled options in the select element.
var options = element.find("option");
for(var pos= 0,index=0;pos<options.length;pos++){
var elem = angular.element(options[pos]);
if(elem.val()!=""){
var locals = {};
locals[attr] = data[index];
elem.attr("disabled", fnDisableIfTrue(scope, locals));
index++;
}
}
};
return {
priority: 0,
require: 'ngModel',
link: function(scope, iElement, iAttrs, ctrl) {
// parse expression and build array of disabled options
var expElements = iAttrs.optionsDisabled.match(
/^\s*(.+)\s+for\s+(.+)\s+in\s+(.+)?\s*/);
var attrToWatch = expElements[3];
var fnDisableIfTrue = $parse(expElements[1]);
scope.$watch(attrToWatch, function(newValue, oldValue) {
if(newValue)
disableOptions(scope, expElements[2], iElement,
newValue, fnDisableIfTrue);
}, true);
// handle model updates properly
scope.$watch(iAttrs.ngModel, function(newValue, oldValue) {
var disOptions = $parse(attrToWatch)(scope);
if(newValue)
disableOptions(scope, expElements[2], iElement,
disOptions, fnDisableIfTrue);
});
}
};
});
注group by
:このソリューションは、誰もが正しく指摘しているようには機能しません。で動作させることを検討している場合は、 @DHlavatyによる以下のソリューションを参照してくださいgroup by
。