Hello Which will take prec...">

Ng-Click vs Href: What is the priority?

If you have a tag like:

   <a href="/hello" ng-click="func()"> Hello </a>

      

Which will take precedence, ng-click or href?

+3


source to share


2 answers


There is no case of precedence between the href and click events here (unless you are talking about the default action priority for the anchor and click event). ng-click

is a directive that is just under the registration of an event handler to the DOM element, and when you click on it, the click event is fired. The default (browser) action of the anchor is to navigate to the URL (if present, absolute or relative) specified in the href. And clicking the anchor triggers the default action unless it's prevented event.preventDefault()

or return false(won't work with handlers registered with angular)

(which doesn't work with angular), which is probably what you're looking for.

In angular, you can pass event from like and you can use that in your handler, or you can even use it in string. ng-click

ng-click="func($event)"



From W3c

Some events are listed as being canceled. For these events, the DOM implementation usually has a default action associated with the event. An example of this is a hyperlink in a web browser. When a user clicks on a hyperlink, the default action usually activates that hyperlink. Before handling these events, an implementation must check the event listeners registered to receive the event and dispatch the event to those listeners. These listeners then have the option to override the default action of the implementation or allow the default action. In the case of a hyperlink in the browser, canceling the action will result in the inactivation of the hyperlink.

Cancellation is done by calling the event preventDefault method. If one or more EventListeners call preventDefault during any phase of the event flow, the default action will be canceled.

+2


source


Actually I just tried it myself and just posted my result because the other answer doesn't really clarify:

href will be executed before ng-click appears. For example:



$scope.redirect = function(){
     window.location.href = 'http://www.stackoverflow.com';
};
<a href="http://www.google.com" ng-click="redirect()">Redirect</a>

      

This will take google instead of stackoverflow.

+1


source







All Articles