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

后端 未结 10 1555
旧时难觅i
旧时难觅i 2020-11-30 18:40

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

相关标签:
10条回答
  • 2020-11-30 19:24

    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

    0 讨论(0)
  • 2020-11-30 19:27

    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.

    0 讨论(0)
  • 2020-11-30 19:30
    <div ng-click="methodName(event)"></div>
    

    IN controller use

    $scope.methodName = function(event) { 
        event.stopPropagation();
    }
    
    0 讨论(0)
  • 2020-11-30 19:31

    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.

    0 讨论(0)
提交回复
热议问题