假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
假设我有一个锚标记,比如
<a href="#" ng-click="do()">Click</a>
如何防止浏览器在AngularJS中导航到# ?
当前回答
/* NG CLICK PREVENT DEFAULT */
app.directive('ngClick', function () {
return {
link: function (scope, element, attributes) {
element.click(function (event) {
event.preventDefault();
event.stopPropagation();
});
}
};
});
其他回答
我找到的最简单的解决方法是:
<a href="#" ng-click="do(); $event.preventDefault()">Click</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对象
很多答案似乎都是多余的。对我来说,这很有效
<a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>
既然你在制作网页应用,为什么还需要链接呢?
把锚换成按钮!
<button ng-click="do()"></button>
你可以在$location的Html5Mode中禁用url重定向来实现这个目标。您可以在页面使用的特定控制器中定义它。 就像这样:
app.config(['$locationProvider',函数($locationProvider) { 美元locationProvider.html5Mode ({ 启用:没错, rewriteLinks:假的, requireBase:假 }); }));