2

I have this situation:

<div ng-click="foo()">
  <a ng-click="bar()">Bar</a>
  <p>Lorem Ipsun</p>
</div>

My problem is, when I click in Bar, foo() is called too. How to call just bar() when click in Bar, and just call foo() when I am not click in bar()?

rafaels88
  • 839
  • 1
  • 6
  • 19

3 Answers3

3

I got my answer in this question:

AngularJS ng-click stopPropagation

Just need to change the HTML to this:

<div ng-click="foo()">
  <a ng-click="bar(); $event.stopPropagation()">Bar</a>
  <p>Lorem Ipsun</p>
</div>
Community
  • 1
  • 1
rafaels88
  • 839
  • 1
  • 6
  • 19
2

ngClick provides the event object in a $event variable. You can call stopPropagation() on it to stop the event from bubbling...

<div ng-click="foo()">
  <a ng-click="bar($event)">Bar</a>
  <p>Lorem Ipsun</p>
</div>

Controller

$scope.bar = function ($event) {
    $event.stopPropagation();
};

JSFiddle

Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
0

Use event.stopPropation() or event.cancelBubble = true to prevent event bubbling Write this code inside the bar() method to prevent calling foo() (parent) method

event = event || window.event // cross-browser event
  if (event.stopPropagation) {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  }

JS Fiddle: http://jsfiddle.net/55sfc/1/

suneetha
  • 827
  • 1
  • 6
  • 14