Maeh Maeh - 1 year ago 169
AngularJS Question

ng-click on parent clicks through children

I have a

element which has another
element as its child.

I added the
directive to the parent, and expected it not to be fired when clicking the child. However, it does.

<div class="outer" ng-click="toggle()">
<div class="inner">You can click through me</div>

Why is it doing this, and how can I avoid it?

Here's a JSFiddle demonstrating the issue

itd itd
Answer Source

You have to cancel event propagation, so the click event of the parent element won't get called. Try:

<div class="outer" ng-click="toggle()">
    <div class="inner" ng-click="$event.stopPropagation()">You can click through me</div>

When you click the child element, its event gets triggered. But it doesn't stop there. First the click event of the child element is triggered, then the click event of the parent element gets triggered and so on. That's called event propagation, To stop event propagation (triggering of the parents click events), you have to use the above function, stopPropagation.

--------EDIT------------------ A working example: DEMO
I added some CSS padding, so the example is clearer. Without padding the child element takes up the whole inner space and you can not click on the parent without clicking on the child.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download