Avoid event propagation in Angular

I had a button inside a box that had an “onclick” feature, which means that both the button and the box had an “onclick” listener. On clicking the box everything worked fine, but on clicking the button the box’s listener also fired its event.

To avoid this, it seems someone developed an “stopPropagation” in jQuery that you can also use in Angular:

app.directive('dontPropagate', function () {
                /*  This directive allows to stop the propagation of an event, 
                    so that if DOM element B is inside DOM element A, 
                    on clicking B the event is not propagated to A (the parent).

                    You have to add the property "dont-propagate='click'" to B, 
                    where "click" is the event you don't want to be propagated.
                */

                return {
                    restrict: 'A',
                    link: function (scope, element, attr) {
                        element.bind(attr.dontPropagate, function (e) {
                            e.stopPropagation();
                        });
                    }
                };
            });

And then the html:

<div id="myBox" ng-click="doSomething()">
      <button dont-propagate='click' ng-click="doSomethingElse()">Caption</button>
</div>

Enjoy!

One thought on “Avoid event propagation in Angular

  • Georgeer

    Feed for question What s the best way to cancel event propagation between nested ng-click calls?

Leave a Reply

Close Bitnami banner
Bitnami