3

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!

1

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks...I've used it like this: <input id="btnModalAddNotes" ng-disabled="notesFrm.$invalid" ng-click="addNotes();notesFrm.$setPristine();notesFrm.$setUntouched();notesFrm.$submitted = false;" type="submit" class="btn btn-info" value="Submit"/>
is it possible to get all the form input value using $scope.myForm ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.