假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
当前回答
尽管雷诺给出了一个很好的解决方案
<a href="#" ng-click="do(); $event.preventDefault()">Click</a>
我个人发现在某些情况下还需要$event.stopPropagation()来避免一些副作用
<a href="#" ng-click="do(); $event.preventDefault(); $event.stopPropagation();">
Click</a>
就是我的解
其他回答
我需要存在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>
借用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();
}
})
}
};
}
])
你可以在$location的Html5Mode中禁用url重定向来实现这个目标。您可以在页面使用的特定控制器中定义它。 就像这样:
app.config(['$locationProvider',函数($locationProvider) { 美元locationProvider.html5Mode ({ 启用:没错, rewriteLinks:假的, requireBase:假 }); }));
ng-click="$event.preventDefault()"
很多答案似乎都是多余的。对我来说,这很有效
<a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>