How to preventDefault on anchor tags?

Let's say I have an anchor tag such as

<a href="#" ng-click="do()">Click</a>

How can I prevent the browser from navigating to # in AngularJS ?


UPDATE : I've since changed my mind on this solution. After more development and time spent working on this, I believe a better solution to this problem is to do the following:

<a ng-click="myFunction()">Click Here</a>

And then update your css to have an extra rule:

a[ng-click]{
    cursor: pointer;
}

Its much more simple and provides the exact same functionality and is much more efficient. Hope that might be helpful to anyone else looking up this solution in the future.


The following is my previous solution, which I am leaving here just for legacy purposes:

If you are having this problem a lot, a simple directive that would fix this issue is the following:

app.directive('a', function() {
    return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
            if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
                elem.on('click', function(e){
                    e.preventDefault();
                });
            }
        }
   };
});

It checks all anchor tags ( <a></a> ) to see if their href attribute is either an empty string ( "" ) or a hash ( '#' ) or there is an ng-click assignment. If it finds any of these conditions, it catches the event and prevents the default behavior.

The only down side is that it runs this directive for all anchor tags. So if you have a lot of anchor tags on the page and you only want to prevent the default behavior for a small number of them, then this directive isn't very efficient. However, I almost always want to preventDefault , so I use this directive all over in my AngularJS apps.


根据ngHref的文档,你应该可以离开href或做href =“”。

<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />

您可以将$ event对象传递给您的方法,并在其上调用$event.preventDefault() ,以使默认处理不会发生:

<a href="#" ng-click="do($event)">Click</a>

// then in your controller.do($event) method
$event.preventDefault()
链接地址: http://www.djcxy.com/p/71702.html

上一篇: 第二个Ajax调用(跨浏览器)

下一篇: 如何防止锚标签默认?