Separate clicks on ion-item from embedded button

Hi all. First, just gotta say, I love ionic. All aspects of it. Great framework, great responsiveness.

I hope I am just missing something simple but I am seeing some unexpected behavior in an ion-item with an embedded right button. I have some markup like this:

<ion-item ng-repeat="loc in locs" ng-click="select({{loc.id}})" class="item-icon-left item-button-right">
   <i class="icon {{loc.icon}}"></i> {{loc.name}}
   <button class="button button-clear button-positive" ng-click="edit('next', $index)">
      <i class="icon {{loc.editIcon}}"></i>
   </button>
</ion-item>

Which dutifully creates a list of items each of which has an icon on the left, a label next to that, and an icon button on the right. I want separate functions to be invoked when the user clicks on the main body of the ion-item (i.e. select()), than when they click on the right button (i.e., edit()).

I have found that clicking directly on the right button invokes the select() function instead of the edit() function as I would expect. I have tried messing with z-index (9999) on the right button, but with no effect.

Am I missing something here? Should I expect the button click to be handled separately and independenty from the ion-item click? If so, any ideas why this isn’t working? Thanks…

It is because click events are bubbeling upwards through your dom.

if you click on edit -> the event bubbles to the ion-item tag and triggers there the select function.

Do the following:

<ion-item ng-repeat="loc in locs" ng-click="select({{loc.id}})" class="item-icon-left item-button-right">
 <i class="icon {{loc.icon}}"></i> {{loc.name}}
 <button class="button button-clear button-positive" ng-click="edit('next', $index, $event)">
   <i class="icon {{loc.editIcon}}"></i>
 </button>
</ion-item>

in your controller for your edit-function

$scope.edit = function (action, $index, $event) {
  $event.stopPropagation();
  // or if this is not working do
  // $event.preventDefault();
}

$event.stopPropagation() -> says “please event, do not bubbling”
$event.preventDefault() -> means “STOP! Do nothing, also not your default behave -> do only what i want you to do!”

In reality it is a little bit more complex, but it works in this way

4 Likes

This works! Thank you loads!