Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs setPristine() not reseting invalid flag

Could anyone help with the the included Plunker??

Simply submit form with only one required field entered. This will trigger the validation errors. Then reset the form which calls both setPristine and setUntouched - both of which are supposed to reset the form however neither clear the validation errors?

I want the form to be cleared of data but also no validation messages to be shown (even though I appreciate as the data is blank it is in fact invalid)

i.e. this reset function

$scope.reset = function(){
    $scope.newQuestion = angular.copy(tempQuestion);

    $scope.forms.setPristine();
    $scope.forms.setUntouched();
};

Plunker example

like image 492
Mad Eddie Avatar asked Dec 02 '25 05:12

Mad Eddie


2 Answers

  1. You are calling the setPristine() & setUntouched() incorrectly.

    Correct syntax is formName.$setPristine() and formName.$setUntouched()

    See this page for more details

  2. Since you are setting attempted=true in the , when you want to reset the form, you must reset the value of attempted as well. This will ensure that the ng-if re-evaluates and does not render the error message.

So the correct code for reset() is as follows:

$scope.reset = function(){
    $scope.newQuestion = angular.copy(tempQuestion);

    $scope.forms.newQuestion.$setPristine();
    $scope.forms.newQuestion.$setUntouched();

    $scope.attempted = false;

  };

Here is the modified Plunker

like image 191
Dinesh Chitlangia Avatar answered Dec 03 '25 17:12

Dinesh Chitlangia


Check your console and you'll see some errors. setPristine() does not exist on the object forms, as your form name is forms.newQuestion. Additionally, the function is $setPristine(). To rid the form of error messages on reset, you can just reset your attempted flag to be false, as that will cause your ng-class expression evaluations to be false.

You will want something like:

$scope.reset = function(){
    $scope.newQuestion = angular.copy(tempQuestion);

    $scope.forms.newQuestion.$setPristine();
    $scope.forms.newQuestion.$setUntouched();
    $scope.attempted = false;
};

Working plunker: http://plnkr.co/edit/PqCVayHTXDlHNufBvrwE?p=preview

like image 40
Joe Pontani Avatar answered Dec 03 '25 19:12

Joe Pontani



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!