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

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

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


当前回答

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

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

其他回答

对于这类事情,我更喜欢使用指令。这里有一个例子

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

eat-click的指令代码:

module.directive('eatClick', function() {
    return function(scope, element, attrs) {
        $(element).click(function(event) {
            event.preventDefault();
        });
    }
})

现在,您可以将eat-click属性添加到任何元素,它将自动获得preventDefault()。

好处:

您不必将丑陋的$event对象传递到do()函数中。 你的控制器更具有单元可测试性,因为它不需要去掉$event对象

如果你使用的是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

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

<a href="javascript:void(0)" ....>
/* NG CLICK PREVENT DEFAULT */

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

如果仍然相关:

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

...

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

...