Angular form reset after validation

I am using angular js to validate in a form for it to work, but after the form is correct, I submit an ajax request and rest with jquery code, so my form still displays correctly. Below is the 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');
        }
    }
});

      

Screenshot Demo

If I set the value to empty with $scope.note['title'] = null;

, it shows an error after clearing.

Screenshot Demo

How can I solve this? what I want - after rest, should return to its original state.

+3


source to share


1 answer


Instead of clearing the form in jQuery, I'd rather use the $setPristine()

on method form

, which will make the form pristine

in angular way. Also you need to clear the form fields 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 script

+1


source







All Articles