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

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

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


当前回答

借用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();
                    }
                })
            }
        };
    }
])

其他回答

借用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();
                    }
                })
            }
        };
    }
])
ng-click="$event.preventDefault()"

很多答案似乎都是多余的。对我来说,这很有效

 <a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>

如果仍然相关:

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

...

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

...

在我的例子中,Angular: 10 -工作

  <a [routerLink]="" (click)="myFunc()"> Click me </a>

更新:此方法将重新加载解析器。由于@Meeker