假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
当前回答
避免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();
});
}
};
});
你可以在$location的Html5Mode中禁用url重定向来实现这个目标。您可以在页面使用的特定控制器中定义它。 就像这样:
app.config(['$locationProvider',函数($locationProvider) { 美元locationProvider.html5Mode ({ 启用:没错, rewriteLinks:假的, requireBase:假 }); }));
ng-click="$event.preventDefault()"
在我的例子中,Angular: 10 -工作
<a [routerLink]="" (click)="myFunc()"> Click me </a>
更新:此方法将重新加载解析器。由于@Meeker
我需要存在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>