Javascript angularjs 表单重置错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26015010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:11:59  来源:igfitidea点击:

angularjs form reset error

javascripthtmlangularjsvalidation

提问by CraZyDroiD

i'm trying to do a form with validations using angularjs and so far i did a good job. But when i commit my reset button all the fields reset except for the error messages i get from my validation part. How can i get rid of all the fields and error messages when i reset my form.

我正在尝试使用 angularjs 做一个带有验证的表单,到目前为止我做得很好。但是当我提交我的重置按钮时,所有字段都会重置,除了我从验证部分得到的错误消息。当我重置表单时,如何摆脱所有字段和错误消息。

This is how it is when i press my reset button

这是我按下重置按钮时的样子

enter image description here

在此处输入图片说明

this is my code

这是我的代码

<div class="page-header"><center><h2>Give us your Feedback</h2></center></div>

    <!-- pass in the variable if our form is valid or invalid -->
    <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>

        <!-- NAME -->
        <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
            <label>Name*</label>
            <input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name"  required>
            <p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block">
                <font color="#009ACD">You name is required.</font>
            </p>
        </div>

         <!-- EMAIL -->
        <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty  }">
            <label>Email</label>
            <input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
            <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">
                <font color="#009ACD">Enter a valid email.</font>
            </p>
        </div>

        <!-- USERNAME -->
        <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
            <label>Description</label>
            <input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username"  ng-minlength="5" ng-maxlength="60" required>
            <font color="white">
                <p ng-show="userForm.username.$error.minlength" class="help-block">
                    <font color="#009ACD">Description is too short.</font>
                </p>
                <p ng-show="userForm.username.$error.maxlength" class="help-block">
                    <font color="#009ACD">Description is too long.</font>
                </p>
            </font>
        </div>

        <div class="col"style="text-align: center">
            <button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
                type="reset"
                ng-click="reset()" padding-top="true"
            >
                Reset
            </button>


            <button class="button button-block button-positive"  style="display: inline-block;width:100px "
                ng-click="submit()"
                padding-top="true"
            >
                Submit
            </button>
        </div>

    </form>
</div>

My controller

我的控制器

.controller('ContactCtrl', function($scope,$state,$ionicPopup, $timeout) {
    $scope.showfeedback = function() {
        $state.go('app.sfeedback');
    };

    $scope.submitForm = function(isValid) {
        $scope.submitted = true;

        // check to make sure the form is completely valid
        if (!isValid) {
            var alertPopup = $ionicPopup.alert({
                title: 'Invalid data entered!',
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Feedback submitted',
            });
        }
    };

    $scope.reset = function() {
        var original = $scope.user;
        $scope.user= angular.copy(original)
        $scope.userForm.$setPristine()
    };
})

回答by Kalhan.Toress

var original = $scope.user;

when resetting :

重置时:

$scope.user= angular.copy(original);
$scope.userForm.$setPristine();

remove

消除

type='reset' in  <button>

here is the Angular Documentationfor form controllers.

这是表单控制器的 Angular文档

回答by Thakhani Tharage

Use the following to reset dirty state

使用以下方法重置脏状态

$scope.form.$setPristine();

Use the following to reset to clear validation

使用以下重置清除验证

$scope.form.$setValidity();

回答by Shannon Hochkins

There's API documentation on the FormController.

FormController上有 API 文档。

This allowed me to find that there's other methods to call such as:

这让我发现还有其他方法可以调用,例如:

$setUntouched()- which is a function I was using if the user has focused on the field, and then left the field, this clears this feature when you run it.

$setUntouched()- 如果用户专注于该领域,然后离开该领域,这是我正在使用的功能,这会在您运行时清除此功能。

I created a simple form reset function which you can use too.

我创建了一个简单的表单重置功能,您也可以使用它。

// Set the following in your controller for the form/page.
// Allows you to set default form values on fields.
$scope.defaultFormData = { username : 'Bob'}
// Save a copy of the defaultFormData
$scope.resetCopy = angular.copy($scope.defaultFormData);
// Create a method to reset the form back to it's original state.
$scope.resetForm =  function() {
    // Set the field values back to the original default values
    $scope.defaultFormData = angular.copy($scope.resetCopy);
    $scope.myForm.$setPristine();
    $scope.myForm.$setValidity();
    $scope.myForm.$setUntouched();
    // in my case I had to call $apply to refresh the page, you may also need this.
    $scope.$apply();
}

In your form, this simple setup will allow you to reset the form

在您的表单中,这个简单的设置将允许您重置表单

<form ng-submit="doSomethingOnSubmit()" name="myForm">
    <input type="text" name="username" ng-model="username" ng-required />
    <input type="password" name="password" ng-model="password" ng-required />
    <button type="button" ng-click="resetForm()">Reset</button>
    <button type="submit">Log In</button>
</form>

回答by Siggen

I had the same problem and used the following code to completely reset the form :

我遇到了同样的问题并使用以下代码完全重置表单:

$scope.resetForm = function(){

    // reset your model data
    $scope.user = ...

    // reset all errors
    for (var att in  $scope.userForm.$error) {
        if ($scope.userForm.$error.hasOwnProperty(att)) {
            $scope.userForm.$setValidity(att, true);
        }
    }

    // reset validation's state
    $scope.userForm.$setPristine(true);
};

回答by Calvin

I went with...

我和...

$scope.form.$setPristine();
$scope.form.$error = {};

Feels hacky... but a lot about angular does.

感觉 hacky ......但很多关于 angular 的内容。

Besides... this was the only thing that worked.

此外……这是唯一有效的方法。

回答by Lorenzo Meriggi

To me using $setPristineto reset the form is a hack. The real solution is to keep it like it should be:

对我来说,使用$setPristine重置表单是一种黑客攻击。真正的解决方案是保持它应有的样子:

<button type="reset" ng-click="reset()"></button>

then in angular:

然后在角度:

var original = angular.copy($scope.user);
$scope.reset = function() {
   $scope.user = angular.copy(original);
};

and that's it.

就是这样。

回答by Kishore Babu

Give us your Feedback

给我们您的反馈

<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>


    <!-- NAME -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
        <label>Name*</label>
        <input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name"  required>
        <p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block"><font color="#009ACD">You name is required.</font></p>


    </div>

     <!-- EMAIL -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty  }">
        <label>Email</label>
        <input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
        <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block"><font color="#009ACD">Enter a valid email.</font></p>
    </div>

    <!-- USERNAME -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
        <label>Description</label>
        <input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username"  ng-minlength="5" ng-maxlength="60" required>
        <font color="white"><p ng-show="userForm.username.$error.minlength" class="help-block"><font color="#009ACD">Description is too short.</font></p>
        <p ng-show="userForm.username.$error.maxlength" class="help-block"><font color="#009ACD">Description is too long.</font></p>
    </div>

    <div class="col"style="text-align: center">
        <button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
        type="reset"
        ng-click="reset()"padding-top="true">Reset</button>


        <button class="button button-block button-positive"  style="display: inline-block; width:100px" ng-click="submit()"padding-top="true">Submit</button>
        </div>

</form>

回答by Archimedes Trajano

I kept the type="reset"in my button. What I did was the ng-click="resetForm(userForm)"(using userFromto match your example) and the controller defines resetForm()as

我一直type="reset"在我的按钮。我所做的是ng-click="resetForm(userForm)"userFrom用于匹配您的示例)并且控制器定义resetForm()

scope.resetForm = function(controller) {
  controller.$commitViewValue();
  controller.$setPristine();
};

Here is what happens:

这是发生的事情:

  1. When the reset button is clicked, it will bring back the original values as specified by the valueattribute on the input
  2. The $commitViewValue()will force the write of whatever is on the view presently to the $modelValueof each field (no need to iterate manually), without this the last $modelValuewould still be stored rather than reset.
  3. The $setPristine()will reset any other validation and submitted fields.
  1. 单击重置按钮时,它将恢复value输入上的属性指定的原始值
  2. $commitViewValue()会迫使无论是在视图目前在写$modelValue每场的(无需手动迭代),如果没有这个最后$modelValue仍然会被存储,而不是重置。
  3. $setPristine()将重置任何其他验证并提交领域。

In my angular-bootstrap-validatorI already had the FormControlleras such I didn't need to pass in the form itself.

在我的angular-bootstrap-validator 中,我已经有了FormController这样的我不需要传递表单本身。

回答by vs7

Use this

用这个

<button type="button" ng-click='resetForm()'>Reset</button>

In Controller

在控制器中

$scope.resetForm = function(){
   $scope.userForm.$dirty = false;
   $scope.userForm.$pristine = true;
   $scope.userForm.$submitted = false;
};

Its working for me

它为我工作

回答by Szabolcs Páll

In case you don't have a master (dynamic models from server), and you want to reset the form but only the binded part of the model you can use this snippet:

如果您没有 master(来自服务器的动态模型),并且您想重置表单但只有模型的绑定部分,您可以使用以下代码片段:

  function resetForm(form){
    _.forEach(form, function(elem){
      if(elem !== undefined && elem.$modelValue !== undefined){
        elem.$viewValue = null;
        elem.$commitViewValue();
      }
    });
  }

And then you can use it with a standard reset buttonlike so:

然后你可以reset button像这样使用它的标准:

<button type="reset" ng-click="resetForm(MyForm);MyForm.$setValidity();">reset</button>