Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark form as unsubmitted in AngularJS

Tags:

angularjs

In AngularJS, is there a way to mark a form that has already been submitted as unsubmitted (so it loses the ng-submitted class?

Background:

In my css, I'm using the angular validation classes to accomplish the following:

  • Initially, all inputs have a normal border color.
  • If the user modifies an input to have an invalid value, set the border color to red.
  • If the user clicks the submit button, set the border color of all invalid inputs to red.

I am accomplishing this like so:

input.ng-dirty.ng-invalid, .ng-submitted .ng-invalid {
    border-color: #F00;
}

That works fine. Now I have a form that submits an asynchronous request, and if the server responds with a success status, I want to clear the form (and effectively reset it to its original state). The problem is when I clear the form, it still has the .ng-submitted class, so all of the required fields have a red border. However I want them all to have a normal border.

I should be able to mark all of the fields as pristine using $setPristine(), but I don't see any way to mark the form as unsubmitted. Is this possible, or do I need to create and maintain my own class for doing this?

like image 892
AJ Richardson Avatar asked Dec 24 '14 22:12

AJ Richardson


1 Answers

You can reset your form and thus mark it as unsubmitted using the following piece of snippet.

Html:

<input type="button" ng-click="reset(form)" value="Reset" />

Angular Script:

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

This was taken from https://docs.angularjs.org/guide/forms

like image 65
Orel Eraki Avatar answered Nov 16 '22 00:11

Orel Eraki