[html] href overrides ng-click in Angular.js

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 question is related to html angularjs anchor markup

The answer is


Just one more hint. If you need real URL (to support browser accessibility) you can do the following:

template:

<a ng-href="{{link}}" ng-click="$event.preventDefault(); linkClicked(link)">{{link}}</a>

directive:

$scope.linkClicked = function(link){
    // your code here
    $location.path(link);
};

In this way your code in linkClicked() will have chance to execute before navigating to the link


I'll add for you an example that work for me and you can change it as you want.

I add the bellow code inside my controller.

     $scope.showNumberFct = function(){
        alert("Work!!!!");
     }

and for my view page I add the bellow code.

<a  href="" ng-model="showNumber" ng-click="showNumberFct()" ng-init="showNumber = false" >Click Me!!!</a>

This example from the angular documentation site just does href without even assigning it to an empty string:

[<a href ng-click="colors.splice($index, 1)">X</a>]

http://docs.angularjs.org/api/ng.directive:select


Please check this

<a href="#" ng-click="logout(event)">Logout</a>

 $scope.logout = function(event)


 {
event.preventDefault();
alert("working..");
}

Did you try redirecting inside the logout function itself? For example, say your logout function is as follows

$scope.logout = function()
{
  $scope.userSession = undefined;
  window.location = "http://www.yoursite.com/#"
}

Then you can just have

<a ng-click="logout()">Sign out</a>

You can also try this:

<div ng-init="myVar = 'www.thesoftdesign'">
        <h1>Tutorials</h1>
        <p>Go to <a ng-href="{{myVar}}">{{myVar}}</a> to learn!</p>
</div>

This worked for me in IE 9 and AngularJS v1.0.7:

<a href="javascript:void(0)" ng-click="logout()">Logout</a>

Thanks to duckeggs' comment for the working solution!


Here is another solution :

<a href="" ng-click="logout()">Sign out</a>

i.e. Just remove the # from the href attribute


//for dynamic elements - if you want it in ng-repeat do below code

angular.forEach($scope.data, function(value, key) {
     //add new value to object
    value.new_url  = "your url";
});

 <div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>

In Angular, <a>s are directives. As such, if you have an empty href or no href, Angular will call event.preventDefault.

From the source:

    element.on('click', function(event){
      // if we have no href url, then don't navigate anywhere.
      if (!element.attr(href)) {
        event.preventDefault();
      }
    });

Here's a plnkr demonstrating the missing href scenario.


You can simply prevent the default behavior of the click event directly in your template.

<a href="#" ng-click="$event.preventDefault();logout()" />

Per the angular documentation,

Directives like ngClick and ngFocus expose a $event object within the scope of that expression.


I don't think you need to remove "#" from href. Following works with Angularjs 1.2.10

<a href="#/" ng-click="logout()">Logout</a>

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.


This works for me

<a href (click)="logout()">
   <i class="icon-power-off"></i>
   Logout
</a>

Just write ng-click before href ..It worked for me

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>_x000D_
    <script>_x000D_
    angular.module("module",[])_x000D_
.controller("controller",function($scope){_x000D_
  _x000D_
  $scope.func =function(){_x000D_
    console.log("d");_x000D_
  }_x000D_
  _x000D_
})</script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-app="module" ng-controller="controller">_x000D_
    <h1>Hello ..</h1>_x000D_
    <a ng-click="func()" href="someplace.html">Take me there</a>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to

Examples related to markup

Table with fixed header and fixed column on pure css href overrides ng-click in Angular.js Section vs Article HTML5 Vertical dividers on horizontal UL menu How do I add space between items in an ASP.NET RadioButtonList How to mark-up phone numbers? How to make PDF file downloadable in HTML link? Is there a way to comment out markup in an .ASPX page?