4

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.

Randy
  • 9,419
  • 5
  • 39
  • 56
Sikandar Sahab
  • 638
  • 3
  • 10
  • 27
  • By default AngularJS stops the form submission, unless your form has an action attribute, which in this case it doesn't. Can you clarify your issue now that you know this? – Giovani Vercauteren Apr 25 '18 at 06:03

2 Answers2

6

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.

Steve
  • 1,903
  • 5
  • 22
  • 30
0

AngularJs exposes the NgSubmit directive which should be used when submitting a form

<form ng-submit="submit()">
    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>

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

        $scope.submit = function() {
            //do your thing
        };

    });
</script>

Warning: Don't combine the use of ng-click and ng-submit

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69