AngularJS – multiple ng-click – event bubbling

All we need is an easy explanation of the problem, so here it is.

In the following example:

  <li ng-repeat="item in items" ng-click="showItem(item)">
    <h3>{{item.title}}</h3>
    <button ng-click="remove(item)">Remove</button>
  </li>

When I click on the button showItem() also is invoked due to event bubbling.
I know that I can use $event to watch for $event.currentTarget and do $event.stopPropagation() etc. but this is very ugly.

Btw. I don’t want to stop propagation on the button (In my case the button is a twitter bootstrap dopdown/button – this is just an example)

How do I stop showItem() from beeing called when I click on the remove button?

EDIT
The ugly fix would be to have:

function remove(item,$event){
  $event.originalEvent.prevent = true;
  // rest of the code
}

function showItem(item,$event){
  if($event.originalEvent.prevent)return;
  // rest of the code
}

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

This solution worked for me (I’m only supporting recent browsers, so I tried to modify the code to be more retro-compatible):

HTML:

<li ng-repeat="item in items" ng-click="showItem(item)">
    <h3>{{item.title}}</h3>
    <button ng-click="remove(item, $event)">Remove</button>
</li>

Scripts:

function remove(item, $event) {
    // do some code here

    // Prevent bubbling to showItem.
    // On recent browsers, only $event.stopPropagation() is needed
    if ($event.stopPropagation) $event.stopPropagation();
    if ($event.preventDefault) $event.preventDefault();
    $event.cancelBubble = true;
    $event.returnValue = false;
}
function showItem(item) {
    // code here
}

EDIT – Added a JSFiddle demo to try it out
http://jsfiddle.net/24e7mapp/1/

Method 2

showItem can be updated to return early if the passed in item no longer exists:

function remove(item) {
  if (-1 == $scope.items.indexOf(item)) {
    // Item no longer exists, return early
    return;
  }
  // Rest of code here
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply