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

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

如何防止浏览器在AngularJS中导航到# ?


当前回答

很多答案似乎都是多余的。对我来说,这很有效

 <a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>

其他回答

根据ngHref的文档,你应该可以去掉href或执行href=""。

<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />

另一种可能是:

<span ng-click="do()">Click</span>

既然你在制作网页应用,为什么还需要链接呢?

把锚换成按钮!

<button ng-click="do()"></button>
/* NG CLICK PREVENT DEFAULT */

app.directive('ngClick', function () {
    return {
        link: function (scope, element, attributes) {
            element.click(function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        }
    };
});

你可以将$event对象传递给你的方法,并在它上面调用$event. preventdefault(),这样默认的处理就不会发生:

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

// then in your controller.do($event) method
$event.preventDefault()