假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
当前回答
很多答案似乎都是多余的。对我来说,这很有效
<a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>
其他回答
如果你使用的是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属性的值退化(当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>
试试这个选项,我可以看到上面还没有列出:
<a href="" ng-click="do()">Click</a>
你可以将$event对象传递给你的方法,并在它上面调用$event. preventdefault(),这样默认的处理就不会发生:
<a href="#" ng-click="do($event)">Click</a>
// then in your controller.do($event) method
$event.preventDefault()
避免href上的事件最安全的方法是将其定义为
<a href="javascript:void(0)" ....>