AngularJS - multiple ng-click - event bubbling

耗尽温柔 提交于 2019-12-03 00:57:13

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/

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!