AngularJS:如何停止ng-click的事件传播? [英] AngularJS: How to stop event propagation from ng-click?

查看:405
本文介绍了AngularJS:如何停止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');
            });

        }
    }
});

是的,在这种情况下有必要进行jQuery方式的绑定.

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.

尝试做:

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

但没有帮助.

例如在这里摆弄- http://jsfiddle.net/STEVER/5bfkbh7u/

推荐答案

在您的情况下,您无法停止传播,因为click事件发生在同一元素上,只有两个不同的处理程序.

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

但是,您可以利用以下事实:在控制器ngClick和指令中,这是相同事件对象.因此,您可以做的是为此事件对象设置一些属性,并在指令中对其进行检查:

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;
    }
}

和指令:

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

演示: http://jsfiddle.net/5bfkbh7u/6/

这篇关于AngularJS:如何停止ng-click的事件传播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆