简体   繁体   中英

How reset form and validation after submitting form (AngularJS)

I want to reset form and all validation messages after submitting a form. Here is plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview

My code is bellow:

Controller:

app.controller('MainCtrl', function($scope) {
  $scope.data={fullName:''};

  $scope.submit=function(){
    console.log('submit')
    $scope.myForm.$setPristine();
    $scope.myForm.$setUntouched();
    $scope.data={fullName:''};
  }
});

HTML:

<body ng-controller="MainCtrl">
<form name="myForm" novalidate>
<div>
    <label class="control-label">Name</label>
    <input
            name="full_name"
            type="text"
            ng-model="data.fullName"
            ng-required="true">

    <p ng-if="myForm.$submitted && myForm.$invalid">Validation message</p>
</div>
<button ng-click="submit()" type="submit">
    Submit
</button>
</form>
</body>

My problem is: when user enters name in the input and clicks on Submit button, validation message shouldn't be shown, because model, form and validation should be resetted. How I can do it?

I tried to use $setPristine() and $setUntouched(), but it doesn't work for me.

Is it possible to do in AngularJS? Thanks!

I'm surrpised but $setpristine() doesn't update $submitted .

This may not be the prettiest solution but seems to work:

app.controller('MainCtrl', function($scope, $timeout) {
  $scope.data = {
    fullName: ''
  };
  $scope.submit = function() {
    console.log('submit')
     $scope.data = {
      fullName: ''
    };
    $timeout(function() {
      $scope.myForm.$setPristine();
      $scope.myForm.$setUntouched();
      $scope.myForm.$submitted = false;
    });   
  }
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM