【问题标题】:Angular js set form to Pristine falseAngular js 将表单设置为 Pristine false
【发布时间】:2016-08-03 21:49:20
【问题描述】:

我有一个 html 表单,我正在使用 Angular js 为 from 中的每个输入添加验证。

但我不想在加载 html 时显示验证错误,直到用户对表单进行一些更改。

所以我的验证如下:

<form name="addApplicationForm" accept-charset="UTF-8" novalidate>
    <input type="text" name="name" ng-model="applicationData.application_name" required>
    <div ng-show="addApplicationForm.name.$invalid && !addApplicationForm.name.$pristine">
      <span class="error" ng-show="addApplicationForm.name.$error.required">Please enter application name.</span>
    </div>
    <button ng-click="submit()">Submit</button>
</form>

这个表格按我的预期工作。现在,如果用户直接单击提交按钮而不对输入进行任何更改,则 $pristine 状态仍然为真,并且现在会显示错误。但在这里我想向用户显示验证错误。

这就是为什么在提交时,我想将表单的 $pristine 状态设置为 false,但我没有看到它的方法。

我也尝试过使用 $dirty 而不是 $pristine 之类的:

<form name="addApplicationForm" accept-charset="UTF-8" novalidate>
    <input type="text" name="name" ng-model="applicationData.application_name" required>
    <div ng-show="addApplicationForm.name.$invalid && !addApplicationForm.name.$dirty">
      <span class="error" ng-show="addApplicationForm.name.$error.required">Please enter application name.</span>
    </div>
    <button ng-click="submit()">Submit</button>
</form>

在提交时,我只是调用 setDirty 方法使表单变脏,因此它会在提交按钮单击时显示错误。

但这里的问题是,我在表单中也有一个重置按钮。单击后,我想清除表单的所有字段,然后我需要将表单的脏标志设置为 false,但我没有任何此类选项。但是对于这种情况,如果我使用 $pristine 我有 $setPristine()。

所以在这种情况下,无论我使用 $dirty 还是 $pristine,我都有一个问题。

请告诉我有什么解决办法。

【问题讨论】:

  • 如果答案不够,请在提交和重置按钮中提供最小的工作 sn-p。

标签: angularjs forms validation


【解决方案1】:

$pristine 和 $dirty 应该一起工作。使用$setPristine 会将表单$pristine 属性设置为true,将$dirty 设置为false。 $setDirty 会适得其反。

您的问题似乎与您正在测试表单字段的$pristine$dirty 属性有关(请参阅https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)。在表单控制器上执行 $setPristine 也会传播到表单的每个字段,而 $setDirty 不会。

你可以看看 angular 的源代码,其中设置了属性(#setPristine 和#setDirty),这部分代码很明确且易于阅读:https://github.com/angular/angular.js/blob/master/src/ng/directive/form.js

【讨论】:

  • 谢谢,它有效。实际上我不知道 $setDirty 会使表单变脏而不是输入字段,如果我使用 setPristine 它会使表单变脏为假。
【解决方案2】:

在这种特定情况下,您无需将 form 设置为任何值。

您只需将支票更改为:

<div ng-show="addApplicationForm.name.$invalid && addApplicationForm.name.$dirty">

我建议你使用this 指令。

还要检查这个tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多