How reset form and validation after submitting form (AngularJS)

10,838

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

Share:
10,838
Anna Miroshnichenko
Author by

Anna Miroshnichenko

I'm a passionate software & Web developer who is interested in exploring new technologies. I have a blog with periodic posts about Web technologies at annmirosh.com.

Updated on June 26, 2022

Comments

  • Anna Miroshnichenko
    Anna Miroshnichenko almost 2 years

    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!