angularjsangularjs-forms

How to stop form submission in AngularJS


You may be amazed why I am intended to do it, but it's necessary to be done. I couldn't solve, so could you please help me.. if yes, let's go!

I have a form, I want that if I click on submit, an action/event should be generated that stops the form submission, and tells me that your form is not submitted. That's it.

Here's my form:

<div ng-app="myApp" ng-controller="myCtrl">

    <form>
        First Name: <input type="text" ng-model="firstName" required><br>
        Last Name: <input type="text" ng-model="lastName" required><br>

        <input type="submit" value="submit form"/>
    </form>

</div>

Here's the AngularJS controller:

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {

        // Execute form submission
        // handle data and prevent redirect

    });
</script>

I regret if I am asking something irrelevant, but I think it can be done to which my reach is not possible for now.

Thanks.


Solution

  • Untested by you can try swapping out for your submit button for

    <button ng-click="submit($event)">Submit form</button>
    

    And then in your controller:

    $scope.submit = function($event) {
      $event.preventDefault();
    }
    

    By not using the default form submission you get to access the event and control whether to continue with it or not.