5

I have come across a method to avoid page refresh after form submission i.e event.preventDefault(); Being very new to Angular I really don't know how to put this syntax in my Angular controller, Is "event" an Angular service? How to use it in the code?

Any help would be appreciated!

2 Answers 2

14

On every angular user interface events like ng-keyup ng-click etc you have access to $event object. f.ex ng-click="myClickHandler($event, otherData). you can call preventDefault on that $event object.

Sign up to request clarification or add additional context in comments.

1 Comment

The docs if anyone is interested -- docs.angularjs.org/guide/expression#-event-
-1

This is very simple. Your HTML Code:

<form (ngSubmit)='onSubmit()'>
  // your code here
  <button type='submit'>Submit</button>
  <button (click)='form.reset();event.preventDefault();'>Cancel</button>
</form>

This form.reset();event.preventDefault(); now prevent cancel button from causing the default action to submit the form.

4 Comments

This answer is for Angular 2+ but the question was asking about AngularJS.
See, the event.preventDefault is a javascript function and is independent of angular version. However the binding used for (ngSubmit) in angularjs will change but the event.preventdefault would remain the same. You can try passing $event on (click) of a button as a parameter of any function.Ex. (click)=doSomething($event).... ```doSomething(event){ event.preventDefault();
The original poster seemed to already know about event.preventDefault(). I downvoted your answer because it doesn't add anything that isn't specific to Angular 2+ which was't the scope of the question. Your answer seems great for any questions about Angular 2+ but isn't relevant here. I agree it's annoying Angular 2+ is so different from AngularJS. Maybe you can find an Angular 2+ question to post this on if it's better than existing answers.
Actually I think an answer that includes an example with $event.preventDefault() inline in the template would be useful. The accepted anwer passes $event to a function which is slightly different. Feel free to edit your answer with some AngularJS code. Maybe keeping part of your answer with an Angular 2+ example isn't the worst thing as long as you address AngularJS which is what the question asked about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.