在AngularJS无形和残疾人领域的验证 [英] Validation of invisible and disabled fields in AngularJS
问题描述
有没有办法做到有条件的验证在AngularJS?我试图解决的问题基本上是单选按钮启用/基于选择禁用输入的列表。下图描绘的问题。第一个文本输入只接受字母,第二个只接受数字。两者都有 NG-模式
和 NG-要求
集。 (上Plunker工作的例子)
Is there any way to do conditional validation in AngularJS? The problem I am trying to solve is basically a list of radio buttons that enable/disable inputs based on the selection. The following image portrays the problem. The first text input accepts only letters, the second one accepts only numbers. Both have ng-pattern
and ng-required
set. (The working example on Plunker)
我想实现的是被选择的单选按钮时,确认关闭了对应的输入字段。
What I would like to achieve is that when the radio button is selected, the validation turns off for the corresponding input field.
我曾希望设置 NG-停用
来真正将prevent无效状态被设定为有问题的表单控件,但很可惜,这是情况并非如此。
I had hoped that setting the ng-disabled
to true would prevent the invalid state from being set for the form controls in question, but alas, that is not the case.
到目前为止,我已经找到了唯一的解决办法是清除输入的时候选择另一种选择和设置 NG-要求
为false。是否有实现这一目标的任何明智的办法还是要拿出DOM元素的唯一解决方案完全?
The only solution I have found so far is to clear the input whenever selecting another choice and setting the ng-required
to false. Is there any sensible way of achieving this or is the only solution to take the elements out of DOM entirely?
推荐答案
试试这个指令:
.directive('disableChildren', function() {
return {
require: '^form',
restrict: 'A',
link: function(scope, element, attrs,form) {
var control;
scope.$watch(function() {
return scope.$eval(attrs.disableChildren);
}, function(value) {
if (!control) {
control = form[element.find("input").attr("name")];
}
if (value === false) {
form.$addControl(control);
angular.forEach(control.$error, function(validity, validationToken) {
form.$setValidity(validationToken, !validity, control);
});
} else {
form.$removeControl(control);
}
});
}
}
})
有关详细信息以及它是如何工作的解释。看看我类似的指令从验证排除隐藏的元素:
For more information and explanation of how it works. Check out my similar directive for excluding hidden elements from validation:
<一个href=\"http://stackoverflow.com/questions/21575051/angular-form-controllers-addcontrol-does-not-update-form-validity-implementin\">implementing指令从验证中排除隐藏的输入元素($问题的AddControl)
我想我们能以某种方式结合这些指令能创建一个可以到处取决于我们如何评估一个前pression使用一般的指令。
I think we could somehow combine these directives to create a general directive that could be used everywhere depending on how we evaluate an expression.
这篇关于在AngularJS无形和残疾人领域的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!