Wednesday, 6 July 2016

AngularJS reset form validations

On submit form in angular js often we need to clear all the fields. In angularJs if you applied form validations on input fields and try to clear all the fields after submit then the form will check automatically all the form validations. And you will feel like form is auto submitting itself. To prevent this issue in angularJs we need to reset the form. I have made few lines of code to prevent check form validations on clear input fields after submit. Check this out:


Step 1: Create resetForm() function and paste following code. And call this function in your submit function's success response.

myApp.controller("itemCtrl", ["$scope", "$state", function ($scope, $state) {

    $scope.item = {};

    $scope.submitForm = function () {
        //write code to submit
        resetForm();
    }
    function resetForm() {
        if ($scope.myForm) {
            $scope.myForm.$setPristine();
            $scope.myForm.$setUntouched();
            $scope.item = {};
        }
    }
}]);

Step 2: Write the following html in your html view to test the resetForm() function.

<form class="form-horizontal"
      name="myForm"
      novalidate>
    <div class="">
        <label class="col-md-3">Message</label>
        <div class="col-md-9" ng-class="{'has-error': myForm.inputMessage.$invalid &&
                                     myForm.inputMessage.$dirty}">
            <input type="text" id="inputMessage" name="inputMessage" class="form-control" required ng-model="item.message" />
            <span class="help-block has-error">
                <span ng-show="myForm.inputMessage.$error.required">
                    Message is required.
                </span>
            </span>
        </div>
        <div id="divSubmit">
            <button type="button" class="btn btn-primary" ng-click="submitForm()" ng-disabled="myForm.$invalid">Submit</button>
        </div>
    </div>
</form>

No comments:

Post a Comment