Here\'s an example. Let\'s say I want to have an image overlay like a lot of sites. So when you click a thumbnail, a black overlay appears over your whole window, and a la
I like the idea of using a directive for this:
.directive('stopEvent', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind('click', function (e) {
e.stopPropagation();
});
}
};
});
Then use the directive like:
<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
<img src="http://some_src" ng-click="nextImage()" stop-event/>
</div>
If you wanted, you could make this solution more generic like this answer to a different question: https://stackoverflow.com/a/14547223/347216
If you insert ng-click="$event.stopPropagation" on the parent element of your template, the stopPropogation will be caught as it bubbles up the tree, so you only have to write it once for your entire template.
<div ng-click="methodName(event)"></div>
IN controller use
$scope.methodName = function(event) {
event.stopPropagation();
}
Sometimes, it may make most sense just to do this:
<widget ng-click="myClickHandler(); $event.stopPropagation()"/>
I chose to do it this way because I didn't want myClickHandler()
to stop the event propagation in the many other places it was used.
Sure, I could've added a boolean parameter to the handler function, but stopPropagation()
is much more meaningful than just true
.