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
"href overrides ng-click in Angular.js"
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 and click
in angular 2.x+) and then it continues to propagate(which eventually triggers the browser to navigate to the url defined with href
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:
<a href="#" ng-click="$event.preventDefault();logout()" />
(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
<a href="#" ng-click="logout($event)" />
And in your logout() method:
logout($event) {
$event.preventDefault();
...
}
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 the href
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:
a {
color:pink;
}
PS1:
Some answers suggest to use:
<a href .../>
href
is an angular directive. When your template is processed by angular this will be converted to
<a href="" .../>
Those two ways are essentially the same.