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

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

其他回答

超文本标记语言

这里纯angularjs:在ng-click函数附近,你可以通过分隔分号来编写preventDefault()函数

<a href="#" ng-click="do(); $event.preventDefault(); $event.stopPropagation();">Click me</a>

JS

$scope.do = function() {
    alert("do here anything..");
}

(or)

你可以这样做,这已经有人讨论过了。

HTML

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

JS

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

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

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

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

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

<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对象

我需要存在href属性的值退化(当js被关闭),所以我不能使用空href属性(或“#”),但上面的代码没有为我工作,因为我需要一个事件(e)变量。我创建了自己的指令:

angular.module('MyApp').directive('clickPrevent', function() {
  return function(scope, element, attrs) {
    return element.on('click', function(e) {
      return e.preventDefault();
    });
  };
});

在HTML中:

<a data-click-prevent="true" href="/users/sign_up" ng-click="openSignUpModal()">Sign up</a>