In AngularJS, what's the difference between ng-pristine and ng-dirty?

What are the differences between ng-pristine and ng-dirty? It seems you can have both to be true:

$scope.myForm.$pristine = true; // after editing the form
145562 次浏览

ng-dirty类告诉您表单已被用户修改,而 ng-pristine类告诉您表单尚未被用户修改。所以 ng-dirtyng-pristine是同一个故事的两面。

类是在任何字段上设置的,而表单有两个属性 $dirty$pristine

您可以使用 $scope.form.$setPristine()函数将表单重置为原始状态(请注意,这是 AngularJS 1.1. x 特性)。

If you want a $scope.form.$setPristine()-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found 译自: 美国《科学》杂志网站(https://stackoverflow. com/questions/12603914/reset-form-to-pristine-state-angularjs-1-0-x)). Basically, this means iterating over all form fields and setting their $dirty flag to false.

希望这个能帮上忙。

Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

如前面的答案所述,ng-pristine表示字段未被修改,而 ng-dirty表示字段已被修改。为什么两者都需要?

假设我们有一张表格,上面有电话和电子邮件地址。无论是电话还是电子邮件都是必需的,而且当用户在每个字段中得到无效数据时,您还必须通知他们。这可以通过同时使用 ng-dirtyng-pristine来实现:

<form name="myForm">
<input name="email" ng-model="data.email" ng-required="!data.phone">
<div class="error"
ng-show="myForm.email.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.email.$invalid && myForm.email.$dirty">
E-mail is invalid
</div>


<input name="phone" ng-model="data.phone" ng-required="!data.email">
<div class="error"
ng-show="myForm.phone.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.phone.$invalid && myForm.phone.$dirty">
Phone is invalid
</div>
</form>

Pristine 告诉我们一个字段是否仍然是处女字段,脏字段告诉我们用户是否已经在相关字段中键入了任何内容:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<form ng-app="" name="myForm">
<input name="email" ng-model="data.email">
<div class="info" ng-show="myForm.email.$pristine">
Email is virgine.
</div>
<div class="error" ng-show="myForm.email.$dirty">
E-mail is dirty
</div>
</form>

注册了单个 keydown 事件的字段不再是处女字段(不再是原始字段) ,因此永远是脏字段。

ng-pristine ($pristine)

如果表单/输入尚未使用,则为 Boolean True (未经用户修改的)

Ng-Dirty < em > ($Dirty)

如果使用了表单/输入,则为 Boolean True (由使用者修改)


$setDirty () ; 将窗体设置为脏状态。 可以调用此方法来添加“ ng-Dirty”类并将表单设置为脏状态(ng-Dirty 类)。此方法将当前状态传播到父窗体。

$setPristine () ; 将窗体设置为其原始状态。 此方法将表单的 $pristine 状态设置为 true,$ty 状态设置为 false,删除 ng-Dirty 类并添加 ng-pristine 类。此外,它还将 $ 递交状态设置为 false。 此方法还将传播到此窗体中包含的所有控件。

当我们希望在保存或重新设置表单后“重用”它时,将表单设置回原始状态通常是有用的。