href overrides ng-click in Angular.js

2019-01-03 02:15发布

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.

15条回答
Luminary・发光体
2楼-- · 2019-01-03 02:54

Please check this

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

 $scope.logout = function(event)


 {
event.preventDefault();
alert("working..");
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-03 02:56

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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-03 02:57

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

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script>
    angular.module("module",[])
.controller("controller",function($scope){
  
  $scope.func =function(){
    console.log("d");
  }
  
})</script>
  </head>

  <body ng-app="module" ng-controller="controller">
    <h1>Hello ..</h1>
    <a ng-click="func()" href="someplace.html">Take me there</a>
  </body>

</html>

查看更多
聊天终结者
5楼-- · 2019-01-03 02:59

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>
查看更多
家丑人穷心不美
6楼-- · 2019-01-03 03:03

Here is another solution :

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

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

查看更多
7楼-- · 2019-01-03 03:03

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

<a href="#/" ng-click="logout()">Logout</a>
查看更多
登录 后发表回答