AngularJS How to prevent button to submit a form

Another tiny good practice that we can easily forget. Let’s say you have a form with two buttons in it. You want that only one of them submit the form and you want the second to execute something on click but not to submit your form.

And you come with this code.

<form ng-controller="YourController" ng-submit="Submit()">
	<button>Submit my form</button>
	<button ng-click="PrintSomethingAwesome()">Print Something Awesome</button>
</form>

As you can notice on this JSFiddle (open your console), both buttons are submitting the form. Concerning right?

###How to fix it? Here comes the easy answer… and the “attribute jungle” of AngularJS :)

You simply need to add what type of button your button is.

Here is the right code.

<form ng-controller="YourController" ng-submit="Submit()">
	<button type="submit">Submit my form</button>
	<button type="button" ng-click="PrintSomethingAwesome()">Print Something Awesome</button>
</form>

Working code on this JSFiddle.

Solution inspired by this useful post.

N.B.: It’s always cleaner/good practice to be clear in your HTML code and you should use <input type="submit"> instead of a <button type="submit">