When both, href and ng-click attributes are defined:
<a href="#" ng-click="logout()">Sign out</a>
the href
attribute takes precedence over ng-click.
I am looking for a way to raise priority of ng-click.
href
is required for Twitter Bootstrap, I can't remove it.
This example from the angular documentation site just does
href
without even assigning it to an empty string:http://docs.angularjs.org/api/ng.directive:select
In Angular,
<a>
s are directives. As such, if you have an emptyhref
or nohref
, Angular will callevent.preventDefault
.From the source:
Here's a plnkr demonstrating the missing
href
scenario.Did you try redirecting inside the logout function itself? For example, say your logout function is as follows
Then you can just have
Just one more hint. If you need real URL (to support browser accessibility) you can do the following:
template:
directive:
In this way your code in linkClicked() will have chance to execute before navigating to the link
There are so many answers for this question here but it seems there is a bit of confusion about what's actually going on here.
Firstly, your premise
is wrong. What is actually happening is that after your click, the click event is first handled by angular(defined by
ng-click
directive in angular 1.x andclick
in angular 2.x+) and then it continues to propagate(which eventually triggers the browser to navigate to the url defined withhref
attribute).(See this for more about event propagation in javascript)If you want to avoid this, then you should cancel the event propagation using the The Event interface's
preventDefault()
method:(This is pure javascript functionality and nothing to do with angular)
Now, this will already solve your problem but this is not the optimal solution. Angular, rightfully, promotes the MVC pattern. With this solution, your html template is mixed with the javascript logic. You should try to avoid this as much as possible and put your logic into your angular controller. So a better way would be
And in your logout() method:
Now the click event will not reach the browser, so it will not try to load the link pointed by
href
. (However note that if the user right clicks on the link and directly opens the link, then there won't be a click event at all. Instead it will directly load the url pointed by thehref
attribute.)Regarding the comments about visited link color in the browsers. Again this has nothing to do with angular, if your
href="..."
points to a visited url by your browser by default the link color will be different. This is controlled by CSS :visited Selector, you can modify your css to override this behaviour:PS1:
Some answers suggest to use:
href
is an angular directive. When your template is processed by angular this will be converted toThose two ways are essentially the same.