假设我在页面上有10个输入元素。我想根据ng-disabled
ng-model
例如:
<input type="text">
<input type="text">
我不想使用包含<fieldset></fieldset>
。
这可能是通过循环之类的吗?
var allInputs = document.getElementsByTagName("input");
$scope.schoolClosed = true;
angular.forEach(allInputs, function(currentInput) {
currentInput.setAttribute("ng-disabled", "schoolClosed");
});
哪会产生如下结果:
<input type="text" ng-disabled="schoolClosed">
<input type="text" ng-disabled="schoolClosed">
我可以像这样通过dom添加角度属性元素吗?
答案 0 :(得分:1)
是的,你可以。您可以为input
元素定义一个指令,该指令将针对所有输入运行。然后你可以有一个服务来存储禁用状态,&#34;订阅&#34;更改指令以直接设置disabled属性而不使用ng-disabled
。
我想你需要让你的服务更复杂,并允许不同的命名组切换,而不是全部或不切换。您甚至可以在包含元素或每个输入上指定组的名称。
您可能还需要检查指令是否是文本输入,因此它不会应用于应用程序中的每个单选按钮,复选框,数字输入等。
var app = angular.module('plunker', []);
app.service('InputDisableService', function() {
this._isDisabled = false;
this._subscribers = [];
this.disabled = function(val) {
if (arguments.length < 1) {
return this._isDisabled;
}
var prev = !!this._isDisabled;
if (prev !== !!val) {
this._isDisabled = !!val;
for (var i = 0, len = this._subscribers.length; i < len; i++) {
this._subscribers[i].call(null, this._isDisabled, prev);
}
}
};
this.toggle = function() {
this.disabled(!this.disabled());
}
this.subscribe = function(callback) {
this._subscribers.push(callback);
// invoke immediately with current value, too
callback(this.disabled());
var self = this;
return {
unsubscribe: function() {
self.subscribers = self.subscribers.filter(function(sub) {
return sub !== callback;
});
}
};
};
});
app.directive('input', function(InputDisableService) {
return {
restrict: 'E',
link: function($scope, $element) {
var sub = InputDisableService.subscribe(function(disabled) {
$element.prop('disabled', disabled);
});
var off = $scope.$on('$destroy', function() {
sub.unsubscribe();
off();
});
}
}
});
app.controller('MainCtrl', function($scope, InputDisableService) {
$scope.inputs = [];
for (var i = 1; i <= 100; i++) {
$scope.inputs.push(i);
}
$scope.toggleDisabled = function() {
InputDisableService.toggle();
};
$scope.isDisabled = function() {
return InputDisableService.disabled();
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<p>Inputs disabled: {{isDisabled()}} <a href="#" ng-click="toggleDisabled(); $event.preventDefault();">Toggle</a></p>
<p ng-repeat="num in inputs">
<label>Input {{num}}
<input type="text">
</label>
</p>
</div>
&#13;