Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 333
Anna Miroshnichenko Avatar asked Aug 04 '26 21:08

Anna Miroshnichenko


1 Answers

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

like image 174
charlietfl Avatar answered Aug 06 '26 11:08

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!