假设我有一个锚标记,比如

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

如何防止浏览器在AngularJS中导航到# ?


当前回答

我一直都是这么做的。效果好极了!

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

其他回答

借用tennisgent的答案。我喜欢你不需要创建一个自定义指令来添加所有的链接。然而,我不能让他在IE8中工作。下面是最终对我有用的方法(使用angular 1.0.6)。

注意,'bind'允许你使用angular提供的jqLite,所以不需要用完整的jQuery来包装。还需要stoppropagation方法。

.directive('a', [
    function() {
        return {
            restrict: 'E',
            link: function(scope, elem, attrs) {

                elem.bind('click', function(e){
                    if (attrs.ngClick || attrs.href === '' || attrs.href == '#'){
                        e.preventDefault();
                        e.stopPropagation();
                    }
                })
            }
        };
    }
])

如果仍然相关:

<a ng-click="unselect($event)" />

...

scope.unselect = function( event ) {
 event.preventDefault();
 event.stopPropagation();
}

...

我找到的最简单的解决方法是:

<a href="#" ng-click="do(); $event.preventDefault()">Click</a>
/* NG CLICK PREVENT DEFAULT */

app.directive('ngClick', function () {
    return {
        link: function (scope, element, attributes) {
            element.click(function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        }
    };
});

你可以在$location的Html5Mode中禁用url重定向来实现这个目标。您可以在页面使用的特定控制器中定义它。 就像这样:

app.config(['$locationProvider',函数($locationProvider) { 美元locationProvider.html5Mode ({ 启用:没错, rewriteLinks:假的, requireBase:假 }); }));