Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preventDefault on anchor tags?

Let's say I have an anchor tag such as

<a href="#" ng-click="do()">Click</a> 

How can I prevent the browser from navigating to # in AngularJS ?

like image 584
Micael Avatar asked Jun 07 '12 11:06

Micael


People also ask

What is the default behavior of anchor tag?

(Default) _blank : usually a new tab, but users can configure browsers to open a new window instead. _parent : the parent browsing context of the current one. If no parent, behaves as _self .

What does event preventDefault () do?

preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

What is preventDefault prevent Dotfault?

The event. preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.


1 Answers

According to the docs for ngHref you should be able to leave off the href or do href="".

<input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> 
like image 53
Chris Avatar answered Sep 21 '22 08:09

Chris