通过触发锚标记的ng-click防止点击元素

时间:2015-07-15 02:25:12

标签: javascript angularjs

我在<span>代码中有一个带有ng-click处理程序的<a>

<a href="/foo/bar">
  <h1>Some title</h1>
  <span ng-click="doSomething()">Say Hi!</span>
</a>

点击此范围后,如何阻止<a>代码导航到其位置?

修改:我找到了答案 - 使用e.preventDefault();而不是e.stopPropagation();

3 个答案:

答案 0 :(得分:0)

尝试使用event.stopPropagation()来阻止事件冒泡DOM树

<span ng-click="doSomething($event)">Say Hi!</span>

控制器

$scope.doSomething = function (event){
    event.stopPropagation();
    // other code
}

答案 1 :(得分:0)

<a href="/foo/bar">
  <h1>Some title</h1>
  <span prevent-click="doSomething()">Say Hi!</span>
</a>

Directive.js

.directive('preventClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind('click', function (e) {
                e.preventDefault();
                scope.$apply(attrs.preventClick);
            }
        }
    }

答案 2 :(得分:0)

答案是使用$event.preventDefault()。这特别是停止HTML元素的默认行为,而不是使用stopPropagation()来阻止事件冒泡DOM树并触发其他处理程序。

在这种情况下,我们将停止特定元素的默认行为,因此preventDefault()是解决方案。