1
votes

I have ng-click event on parent DIV, which calls function. I want this event to be triggered only if the parent div is clicked, not if the child div is clicked. So, if the area clicked inside parent covers child div, event should not trigger. Now, click on div2 triggers event.

My example is here on code pen

Html structure:

<div id="div1" class="div1" ng-app="appModule" ng-controller="appController" ng-click="test();">
  <div id="div2" class="div2">
  </div>
</div>

There is div1 (parent div) and div2 inside this div (child div). I've put ng-click on parent div, because I need it to be triggered everywhere on the parent, only on the div2 not. How to achieve this with angular?

3
This is the problem of JavaScript Event Bubbling.Rohan Veer
Add a click listener on child element and use stopPropogation to stop event bubbling.Rohan Veer

3 Answers

1
votes

You can check if the target element and currentTarget is same

HTML

<div id="div1" class="div1" ng-app="appModule" ng-controller="appController" ng-click="test($event);"> // Passing event object
  // Rest of code
</div>

JS

$scope.test = function(e) {
  if (e.target == e.currentTarget) {  // checking if target and currentTarget is same
    alert("test!");
  } else {
    //Rest of code

  }
1
votes

You can use $event.target to validate which element is clicked. then execute the operation. Here in example, I have used id property

<div id="div1" class="div1" ng-app="appModule" ng-controller="appController" ng-click="test($event);">
  <div id="div2" class="div2">
  </div>
</div>

Script

$scope.test = function(event) {
    if (event.target.id == 'div1') {
        alert("test!");
    }
} 

DEMO

1
votes

You can use ng-click="$event.stopPropagation()" to achieve this.If u do this , even if you click on a child element , the event doesnt propagate to Parent element.

<div id="div1" class="div1" ng-app="appModule" ng-controller="appController" ng-click="test();">
<div id="div2" ng-click="$event.stopPropagation()" class="div2">
  </div>
</div>