我有一个html选择选项
<select>
<option ng-repeat="field in filter.fields" value="{{field.id}}">{{field.name}}</option>
</select>
我正在从ng-repeat迭代,我想基于一个可选择的字段来禁用选项
<select>
<option ng-repeat="field in filter.fields" {field.selectable==true?enable:disable} value="{{field.id}}">{{field.name}}</option>
</select>
我怎样才能用角度来实现这个目标?
答案 0 :(得分:27)
假设您有这样的结构:
$scope.filter = {
fields: [
{id: 1, name: "a", selectable: false},
{id: 2, name: "asdf", selectable: true},
{id: 3, name: "qwet", selectable: false},
{id: 4, name: "qnjew", selectable: true},
{id: 5, name: "asdjf", selectable: false}
]
};
这应该适合你:
<select>
<option ng-repeat="field in filter.fields" ng-disabled="field.selectable" value="{{field.id}}">{{field.name}}</option>
</select>
答案 1 :(得分:11)
虽然ng-disabled属性在技术上有效,但在使用ng-repeat on选项时可能会遇到错误。这是一个众所周知的问题,正是角度团队创建ng-options的原因。将ng-options和ng-disabled一起使用还没有角度实现,但 Alec LaLonde 创建了这个可以添加和使用的自定义指令。 See the issue forum here: https://github.com/angular/angular.js/issues/638和jsfiddle from that post。
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';
}
答案 2 :(得分:3)
这实际上是一个相当古老的问题。在Angular(angular 1.4+)的更高版本中,您有ngOptions指令。这是链接: -
https://docs.angularjs.org/api/ng/directive/ngOptions
现在有一种处理这种情况的语法: -
label disable when disable for value in array track by trackexpr
我想我会把它放在以防其他人访问此页面。