本文介绍了使用 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>

解决方案

因此,当内部无效时,没有办法使外部形式自动有效(通过$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>
解决方案

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

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 跳过嵌套表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 15:16