1

I have a <span> with a ng-click handler inside of an <a> tag.

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

When this span is clicked, how can I prevent the <a> tag from navigating to its location?

Edit: I found the answer - use e.preventDefault(); not e.stopPropagation();.

Don P
  • 60,113
  • 114
  • 300
  • 432
  • Possible duplicate: http://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli – Alberto I.N.J. Jul 15 '15 at 02:34
  • Not a duplicate. That question is asking about a *child* anchor tag triggering a parent's on-click handler. My question is the reverse - how do you stop a child from triggering a *parent* anchor. The solution is different: In their question you use `event.stopPropagation()`, in mine you use `event.preventDefault();`. – Don P Jul 16 '15 at 01:11

3 Answers3

0

Try using event.stopPropagation() which prevents the event from bubbling up the DOM tree

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

controller

$scope.doSomething = function (event){
    event.stopPropagation();
    // other code
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
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);
            }
        }
    }
tuckerjt07
  • 902
  • 1
  • 12
  • 31
0

The answer is to use $event.preventDefault(). This is particular to stopping the default behavior of an HTML element, vs using stopPropagation() to stop an event from bubbling up the DOM tree and triggering other handlers.

In this case we are stopping the default behavior of a particular element, so preventDefault() is the solution.

Don P
  • 60,113
  • 114
  • 300
  • 432