Last Updated: September 09, 2019
·
77.47K
· muszynskis

AngularJS: How to prevent form submission after click on button?

Inside our form in view:

<button ng-click="submit($event)">SEND ME</button>

Defining our function in controller:

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

8 Responses
Add your response

Hey, I think you're naming your functions badly.

There's a directive called ng-submit which you can use. You cannot mix it with action="" however as angular will process it normally.

<form name="someform" ng-submit="someform.$valid && submit(someform)" novalidate>

then

$scope.submit = function(form){ // angular will do whatever you say in here. // default form action prevented. }

over 1 year ago ·

Thanks for your comment! I use the technique you introduced and it usually works pretty good. However, once I noticed it didn't work in my modal box and the only solution was to use $event.preventDefault() function, but I will look at it once again.

over 1 year ago ·

Hello. There is another way to do that i think is the right way. Is just add the attribute "type=button" to the <button> element. If the type is not explicit defined, the button will act just like a "type=submit" (the one that submit the form).

Source from W3C: http://www.w3.org/TR/html-markup/button.html

over 1 year ago ·

Thank you @diegozoracky for your answer. I have just checked it and it works like a charm!

over 1 year ago ·

@muszynskis Good ;)

over 1 year ago ·

All you have to do is to remove action attribute from you form and then angular itself would preven default form submission.

over 1 year ago ·

If you make the submit by ajax, you can control the sending with a property (variable):
$scope.boolLoadedData = false;<br>
Just change the variable to FALSE when starts the process and then change it to TRUE when it is success.

over 1 year ago ·

godd one....!!!

over 1 year ago ·