Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 945
Stepan Suvorov Avatar asked Feb 18 '15 14:02

Stepan Suvorov


1 Answers

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/

like image 187
dfsq Avatar answered Oct 29 '22 20:10

dfsq