Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent parent click event when the user clicks on his child element? AngularJS

I have a <div> with a ng-click but this <div> have a child element with also a ng-click directive. The problem is that the click event on the child element trigger also the click event of the parent element.

How can I prevent the parent click event when I click on his child?

Here is a jsfiddle to illustrate my situation.

Thank you in advance for your help.

EDIT

Here is my code:

<body ng-app ng-controller="TestController">
<div id="parent" ng-click="parentClick()">
    <div id="child" ng-click="childClick()"></div>

    <p ng-bind="elem"></p>
</div>

<div><p style="text-align:center" ng-bind="childElem"></p></div>
</body>

<script>
function TestController($scope) {
    $scope.parentClick = function() {
        $scope.elem = 'Parent';
    }

    var i = 1;
    $scope.childClick = function() {
        $scope.elem = 'Child';
        $scope.childElem = 'Child event triggered x' + i;
        i++;
    }
}
</script>
like image 324
KeizerBridge Avatar asked Oct 22 '15 12:10

KeizerBridge


People also ask

How do you stop event propagation from parent to child in react?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.

What is event stopPropagation () Angularjs?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.


1 Answers

You should use the event.stopPropagation() method. see: http://jsfiddle.net/qu86oxzc/3/

<div id="child" ng-click="childClick($event)"></div>

$scope.childClick = function($event) {
    $event.stopPropagation();
    ...
}
like image 179
Pieter Willaert Avatar answered Oct 07 '22 17:10

Pieter Willaert