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

KeizerBridge picture KeizerBridge · Oct 22, 2015 · Viewed 13.2k times · Source

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>

Answer

Pieter Willaert picture Pieter Willaert · Oct 22, 2015

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();
    ...
}