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

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

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


当前回答

如果你使用的是Angular 8或更高版本,你可以创建一个指令:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[preventDefault]'
})
export class PreventDefaultDirective {

  @HostListener("click", ["$event"])
  public onClick(event: any): void
  {
    console.log('click');
    debugger;
      event.preventDefault();
  }

}

在组件的锚标记上,你可以这样连接它:

  <a ngbDropdownToggle preventDefault class="nav-link dropdown-toggle" href="#" aria-expanded="false" aria-haspopup="true" id="nav-dropdown-2">Pages</a>

App Module应该有它的声明:

import { PreventDefaultDirective } from './shared/directives/preventdefault.directive';


@NgModule({
  declarations: [
    AppComponent,
    PreventDefaultDirective

其他回答

另一种可能是:

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

避免href上的事件最安全的方法是将其定义为

<a href="javascript:void(0)" ....>

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