虽然 ng-disabled 属性在技术上会起作用,但在选项上使用 ng-repeat 时可能会遇到错误。这是一个众所周知的问题,也正是 Angular 团队创建 ng-options 的原因。还没有将 ng-options 和 ng-disabled 一起使用的角度实现,但是Alec LaLonde创建了这个自定义指令,您可以添加和使用它。请参阅此处的问题论坛:https://github.com/angular/angular.js/issues/638和该帖子中的 jsfiddle。
angular.module('myApp', [])
.directive('optionsDisabled', [ '$parse', function($parse) {
var disableOptions = function($scope, attr, $element, data, fnDisableIfTrue) {
$element.find('option:not([value="?"])').each(function(i, e) { //1
var locals = {};
locals[attr] = data[i];
$(this).attr('disabled', fnDisableIfTrue($scope, locals));
});
};
return {
priority: 0,
require: 'ngModel',
link: function($scope, $element, attributes) { //2
var expElements = attributes.optionsDisabled.match(/^\s*(.+)\s+for\s+(.+)\s+in\s+(.+)?\s*/),
attrToWatch = expElements[3],
fnDisableIfTrue = $parse(expElements[1]);
$scope.$watch(attrToWatch, function(newValue, oldValue) {
if (!newValue) return;
disableOptions($scope, expElements[2], $element, newValue, fnDisableIfTrue);
}, true);
$scope.$watch(attributes.ngModel, function(newValue, oldValue) { //3
var disabledOptions = $parse(attrToWatch)($scope);
if (!newValue) return;
disableOptions($scope, expElements[2], $element, disabledOptions, fnDisableIfTrue);
});
}
};
}
]);
//1 refresh the disabled options in the select element
//2 parse expression and build array of disabled options
//3 handle model updates properly
function OptionsController($scope) {
$scope.ports = [{name: 'http', isinuse: true},
{name: 'test', isinuse: false}];
$scope.selectedport = 'test';
}