AngularJS ng-click stopPropagation AngularJS ng-click stopPropagation angularjs angularjs

AngularJS ng-click stopPropagation


ngClick directive (as well as all other event directives) creates $event variable which is available on same scope. This variable is a reference to JS event object and can be used to call stopPropagation():

<table>  <tr ng-repeat="user in users" ng-click="showUser(user)">    <td>{{user.firstname}}</td>    <td>{{user.lastname}}</td>    <td>      <button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">        Delete      </button>    </td>                </tr></table>

PLUNKER


An addition to Stewie's answer. In case when your callback decides whether the propagation should be stopped or not, I found it useful to pass the $event object to the callback:

<div ng-click="parentHandler($event)">  <div ng-click="childHandler($event)">  </div></div>

And then in the callback itself, you can decide whether the propagation of the event should be stopped:

$scope.childHandler = function ($event) {  if (wanna_stop_it()) {    $event.stopPropagation();  }  ...};


I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".

You would use it like this:

<table>  <tr ng-repeat="user in users" ng-click="showUser(user)">    <td>{{user.firstname}}</td>    <td>{{user.lastname}}</td>    <td isolate-click>      <button class="btn" ng-click="deleteUser(user.id, $index);">        Delete      </button>    </td>                </tr></table>

Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:

<span isolate-click>    <button class="btn" ng-click="deleteUser(user.id, $index);">        Delete    </button></span>

Here is the directive's code:

angular.module('awesome', []).directive('isolateClick', function() {    return {        link: function(scope, elem) {            elem.on('click', function(e){                e.stopPropagation();            });        }   };});