Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs submit form and reset $pristine state

Taken this form as example http://plnkr.co/edit/fHEBw6dDdG3IVgnmCLb7?p=preview
How can I put the $pristine state of the form to true after the SAVE DRAFT button is pressed?

like image 838
rascio Avatar asked Dec 10 '13 09:12

rascio


People also ask

What is$ setPristine?

$setPristine();Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.

What is$ dirty in AngularJS?

$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.

What is form controller?

A form controller is triggered either upon the form's submission or on adding or updating input in a form field. When a user adds or updates an input value in a form field or clicks the submit or cancel button in the form, the form function associated with this function is triggered to execute the intended action.


2 Answers

You can call $setPristine on the form: http://plnkr.co/edit/wXaFXtuhNH6d4SP2uArm?p=preview

<button ng-click="reset(); form.$setPristine()">RESET</button>
<button ng-click="update(user); form.$setPristine()">SAVE</button>

Or you can call the method in your controller (after ensuring that the form exists):

  $scope.update = function(user) {
    $scope.master= angular.copy(user);
    if ($scope.form) $scope.form.$setPristine();
  };

  $scope.reset = function() {
    $scope.user = angular.copy($scope.master);
    if ($scope.form) $scope.form.$setPristine();
  };

Demo: http://plnkr.co/edit/Mau7uuDfPlzcn418OdWh?p=preview

like image 59
musically_ut Avatar answered Oct 27 '22 07:10

musically_ut


I've noticed that the reset() won't clear the email input unless it's valid. I've tried another approach instead:

<button type="reset" ng-click="form.$setPristine()">RESET</button>
<button ng-click="update(user); form.$setPristine()">SAVE</button>
like image 33
Lucas Engel Avatar answered Oct 27 '22 06:10

Lucas Engel