【问题标题】:AngularJs setPristine() not reseting invalid flagAngularJs setPristine()不重置无效标志
【发布时间】:2015-08-12 15:23:48
【问题描述】:

任何人都可以帮助使用随附的 Plunker 吗?

只需输入一个必填字段即可提交表单。这将触发验证错误。然后重置调用 setPristine 和 setUntouched 的表单 - 两者都应该重置表单但都不能清除验证错误?

我希望清除表单中的数据,但也不显示验证消息(尽管我很感激,因为数据是空白的,但实际上是无效的)

即这个重置函数

$scope.reset = function(){
    $scope.newQuestion = angular.copy(tempQuestion);

    $scope.forms.setPristine();
    $scope.forms.setUntouched();
};

Plunker example

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:
    1. 您错误地调用了 setPristine() 和 setUntouched()。

      正确的语法是formName.$setPristine()formName.$setUntouched()

      详情请见this page

    2. 由于您在 中设置attempted=true,当您要重置表单时,您还必须重置attempted 的值。这将确保ng-if 重新评估并且不会呈现错误消息。

    所以reset()的正确代码如下:

    $scope.reset = function(){
        $scope.newQuestion = angular.copy(tempQuestion);
    
        $scope.forms.newQuestion.$setPristine();
        $scope.forms.newQuestion.$setUntouched();
    
        $scope.attempted = false;
    
      };
    

    这里是修改后的Plunker

    【讨论】:

    • 一个小小的吹毛求疵;我会使用 form.$submitted 而不是像您在 plunker 中那样“尝试”。
    【解决方案2】:

    检查您的控制台,您会看到一些错误。 setPristine() 在对象 forms 上不存在,因为您的表单名称是 forms.newQuestion。另外,函数是$setPristine()。要消除重置时错误消息的形式,您只需将 attempted 标志重置为 false,因为这将导致您的 ng-class 表达式评估为 false。

    你会想要这样的:

    $scope.reset = function(){
        $scope.newQuestion = angular.copy(tempQuestion);
    
        $scope.forms.newQuestion.$setPristine();
        $scope.forms.newQuestion.$setUntouched();
        $scope.attempted = false;
    };
    

    工作人员:http://plnkr.co/edit/PqCVayHTXDlHNufBvrwE?p=preview

    【讨论】:

    • 谢谢 - 我冲着 Plunker 的例子,之前在我的应用程序 $setPristine() 中尝试过,但它没有工作。似乎 $setUntouched 也可以被注释掉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    相关资源
    最近更新 更多