hvy1rg
Last Updated: August 23, 2016
·
47.46K
· muszynskis
Profil mini

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();
}
Say Thanks
Respond

8 Responses
Add your response

15973
Bfdcc4c9e3c21427364e968673b3811b

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 ·
15979
Profil mini

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 ·
17503
None

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 ·
17505
Profil mini

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

over 1 year ago ·
17512
None

@muszynskis Good ;)

over 1 year ago ·
17838
0  nwrbmti4azupbzsindfbr9sviccoxdstrg7brlplsnf38ovftmpdul q6ghgihncbwaeyixqyc0

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 ·
18249
None

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 ·
24987
0 cv5yq4hioenmubezg4c qucepw3v2qzz8jliqu1miez51k74apvkhrbb ite71mn jbcwptf jxe

godd one....!!!

over 1 year ago ·