使用 AngularJS 跳过嵌套表单验证 [英] Skip nested forms validation with AngularJS
问题描述
如何使用 AngularJS 跳过嵌套表单的验证?即使其子表单无效,我也必须使外部表单有效.
在下面的示例中,外部表单应该是有效的(fOuter.$valid
必须为真).默认情况下,它不是.有选择吗?
代码(jsFiddle):
<ng-form name="fOuter"><h3>外层形式(valid={{fOuter.$valid}})</h3><input type="text" name="txtOuter" ng-model="outer" placeholder="(required)" required/><ng-form name="fInner"><h3>内部形式(valid={{fInner.$valid}})</h3><input type="text" name="txtInner" ng-model="inner" placeholder="(required)" required/></ng-form></ng-form>
在 Angular 表单中可以嵌套.这意味着当所有子表单也都有效时,外部表单也是有效的.
因此,当内部无效时,没有办法使外部形式自动有效(通过$valid
键).
尝试使用error.required
<h3>外层形式(valid={{!fOuter.txtOuter.$error.required}})</h3>
演示 小提琴
来自 Angular ngForm 文档:
另一种方式应该是使用控制器,例如:
外层形式(valid={{isOuterFormValid}})
控制器
$scope.isOuterFormValid = true;//在这里,在每个输入上添加侦听器并更改标志 `isOuterFormValid`...
How can I skip validation of nested forms with AngularJS? I have to make an outer form valid even when its child form is invalid.
In the example below outer form should be valid (fOuter.$valid
must be true). By default, it is not. Is there an option?
Code (jsFiddle):
<div ng-app ng-controller="Ctrl">
<ng-form name="fOuter">
<h3>Outer form (valid={{fOuter.$valid}})</h3>
<input type="text" name="txtOuter" ng-model="outer" placeholder="(required)" required />
<ng-form name="fInner">
<h3>Inner form (valid={{fInner.$valid}})</h3>
<input type="text" name="txtInner" ng-model="inner" placeholder="(required)" required />
</ng-form>
</ng-form>
</div>
In Angular forms can be nested. This means that the outer form is valid when all of the child forms are valid as well.
So there is no way to make outer form to be valid automatically (through $valid
key) when one of inner invalid.
Try to use error.required
<h3>Outer form (valid={{!fOuter.txtOuter.$error.required}})</h3>
Demo Fiddle
From Angular ngForm docs:
The other way should be to use controller, like:
<h3>Outer form (valid={{isOuterFormValid}})</h3>
controller
$scope.isOuterFormValid = true;
// here, add listener on each input and change flag `isOuterFormValid`
...
这篇关于使用 AngularJS 跳过嵌套表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!