Manwal
Manwal

Reputation: 23836

Angular form reset after validation

I am using angular js for validation on form its working fine but after form is valid i am sending ajax request and resting it with jquery code, So my form still shows valid. Here is following js snippet:

var myApp = angular.module('myApp', []);

myApp.controller('myController', function ($scope) {    

    $scope.clearForm = function (formId) {
        $(formId)[0].reset();
        console.log($scope.note['title'])
        //$scope.note['title'] = null;
    };

    $scope.submitForm = function () {
        if ($scope.noteForm.$valid) {
            alert("valid");
            //ajax request
            $scope.clearForm('#noteForm');
        }
    }
});

Fiddle Demo

If i am setting blank value with $scope.note['title'] = null; it shows error after clearing.

Fiddle Demo

How can i resolve this? what i want is after resting from should goes to initial state.

Upvotes: 3

Views: 118

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Rather than clearing form in jQuery, I'd prefer you to use $setPristine() method on form that will make form as pristine in angular way. Also you need to clear form fields just by doing $scope.note = {}.

Code

$scope.clearForm = function (formId) {
    $scope.noteForm.$setPristine(); //you should use setPristine that will make for pristine
    $scope.note = {}; //this will clear a form values.
};

Demo Fiddle

Upvotes: 1

Related Questions