rafaels88
rafaels88

Reputation: 839

How to prevent ng-click in container not be triggered by elements inside in AngularJS

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()?

Upvotes: 2

Views: 2210

Answers (3)

suneetha
suneetha

Reputation: 827

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/

Upvotes: 0

rafaels88
rafaels88

Reputation: 839

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>

Upvotes: 3

Anthony Chu
Anthony Chu

Reputation: 37520

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

Upvotes: 2

Related Questions