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

查看:29
本文介绍了AngularJS:如何从 ng-click 停止事件传播?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的指令:

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/

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

推荐答案

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

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天全站免登陆