AngularJS: How to stop event propagation from ng-click?

拥有回忆 提交于 2019-12-12 07:53:48

问题


I have directive that does something like so:

app.directive('custom', function(){
    return {
        restrict:'A',
        link: function(scope, element){
            element.bind('click', function(){
                alert('want to prevent this');
            });

        }
    }
});

yes, it's necessary to do jQuery-way binding for this case.

And now I want to stop this event(click) propagation if some condition met.

Tried to do:

  $event.stopPropagation();
  $event.preventDefault();

but it did not help.

here fiddle for example - http://jsfiddle.net/STEVER/5bfkbh7u/


回答1:


In your case you can't stop propagtion because click event happens on the same element, there are just two different handlers.

However you can leverage the fact that this is the same event object in both controller ngClick and in directive. So what you can do is to set some property to this event object and check for it in directive:

$scope.dosomething = function($event){
    $event.stopPropagation();
    $event.preventDefault();
    alert('here');

    if (someCondtion) {
        $event.stopNextHandler = true;
    }
}

and in directive:

link: function(scope, element){
    element.bind('click', function(e) {
        if (e.stopNextHandler !== true) {
            alert('want to prevent this');    
        }
    });            
}

Demo: http://jsfiddle.net/5bfkbh7u/6/




回答2:


Have you tried lowering the priority of this directive to make sure it binds after the ng-click directive? I assume the events fire in the order they were bound which is in turn determined by the priority of the ng-click directive vs your directive.

You also need stopImmediatePropagation to prevent any more handlers on the same element from firing. stopPropagation just prevents the event propagating to parent handlers.




回答3:


Use e.stopImmediatePropagation();
elem.bind('click', function (e) {
  if (disable(scope)){
    e.stopImmediatePropagation();
    return false;
  }

  return true;
});



回答4:


there isnt any event propagation here as you have button and you are having to events on the same element this isnt going to parent element of child element, i.e no event bubbling or event capturing is here




回答5:


You attach both events to the button. Check the element when you register the second event

<div ng-controller="mainCtrl" custom>
    Hi! I'm the parent.
    <button ng-click="dosomething($event)">BUTTON</button>
</div>

Showcase



来源:https://stackoverflow.com/questions/28586231/angularjs-how-to-stop-event-propagation-from-ng-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!