【问题标题】:$setPristine() method in Angular 1.2.1 doesn't appear to work as intendedAngular 1.2.1 中的 $setPristine() 方法似乎没有按预期工作
【发布时间】:2013-11-29 09:14:39
【问题描述】:

我正在尝试使用 AngularJS 中的 $setPristine 函数重置文本框,但它似乎没有产生预期的行为。

我的表单如下所示:

<form name="addInviteForm" ng-controller="InviteCtrl" ng-submit="sendInvitation(userEmail)">

      Pristine? {{addInviteForm.$pristine}}

      <!-- email input -->
      <div>
        <input type="email" name="email" ng-model="userEmail" placeholder="Enter email here"  class="line-item-input see" required>
        <span class="error" ng-show="addInviteForm.email.$error.email" style="color:red">Invalid Email</span>
      </div>

      <!-- submit button -->
      <input type="submit" name="send" class="btn btn-success center" value="Send Invitation">
</form>

以及我的控制器中对应的代码:

$scope.sendInvitation = function(userEmail) {

        // do some work here ...

        // hmm, this doesn't seem to work ...
        $scope.addInviteForm.$setPristine();
    };

虽然表单显示$pristine在表单输入时设置为true,然后在文本框中输入数据时设置为false,但在提交表单后确实显示$pristine已设置为 true .... 但文本框中的值仍保持按下提交按钮之前的状态。

我在这里错过了什么?

【问题讨论】:

    标签: javascript angularjs dom


    【解决方案1】:

    $setPristine 不会从表单中的控件中清除值:

    来自the docs

    将表单设置为其原始状态。

    可以调用此方法来删除“ng-dirty”类并设置 形成其原始状态(ng-pristine 类)。这种方法也会 传播到此表单中包含的所有控件。

    当我们需要时,将表单设置回原始状态通常很有用 在保存或重置表单后“重新使用”表单。

    从上面的描述可以看出,$setPristine 只是改变了表单的状态(从而重置了应用于表单中每个控件的 css)。

    如果你想清除每个控件的值,那么你需要在代码中为 each 做。

    This plunker 显示$setPristine 的实际应用。

    【讨论】:

    • 谢谢。将userEmail 绑定到InviteCtrl 范围内的变量并在提交时重置该变量似乎已经成功了。
    • 虽然我会说,文档并没有说得很清楚。即,控件的“状态”和控件的当前“值”之间的语义区别并不明显......
    猜你喜欢
    • 1970-01-01
    • 2020-09-15
    • 2016-01-24
    • 1970-01-01
    • 2022-12-17
    • 2021-06-07
    • 2013-02-10
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多