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

后端 未结 10 1554
旧时难觅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:10

    You can register another directive on top of ng-click which amends the default behaviour of ng-click and stops the event propagation. This way you wouldn't have to add $event.stopPropagation by hand.

    app.directive('ngClick', function() {
        return {
            restrict: 'A',
            compile: function($element, attr) {
                return function(scope, element, attr) {
                    element.on('click', function(event) {
                        event.stopPropagation();
                    });
                };
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-30 19:18

    In my case event.stopPropagation(); was making my page refresh each time I pressed on a link so I had to find another solution.

    So what I did was to catch the event on the parent and block the trigger if it was actually coming from his child using event.target.

    Here is the solution:

    if (!angular.element($event.target).hasClass('some-unique-class-from-your-child')) ...
    

    So basically your ng-click from your parent component works only if you clicked on the parent. If you clicked on the child it won't pass this condition and it won't continue it's flow.

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

    Use $event.stopPropagation():

    <div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
        <img src="http://some_src" ng-click="nextImage(); $event.stopPropagation()" />
    </div>
    

    Here's a demo: http://plnkr.co/edit/3Pp3NFbGxy30srl8OBmQ?p=preview

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

    If you don't want to have to add the stop propagation to all links this works as well. A bit more scalable.

    $scope.hideOverlay( $event ){
    
       // only hide the overlay if we click on the actual div
       if( $event.target.className.indexOf('overlay') ) 
          // hide overlay logic
    
    }
    
    0 讨论(0)
  • 2020-11-30 19:23

    What @JosephSilber said, or pass the $event object into ng-click callback and stop the propagation inside of it:

    <div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
      <img src="http://some_src" ng-click="nextImage($event)"/>
    </div>
    
    $scope.nextImage = function($event) {
      $event.stopPropagation();
      // Some code to find and display the next image
    }
    
    0 讨论(0)
  • 2020-11-30 19:23

    This works for me:

    <a href="" ng-click="doSomething($event)">Action</a>
    
    this.doSomething = function($event) {
      $event.stopPropagation();
      $event.preventDefault();
    };
    
    0 讨论(0)
提交回复
热议问题