javascript AngularJS:如何从 ng-click 停止事件传播?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28586231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS: How to stop event propagation from ng-click?
提问by Stepan Suvorov
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.
是的,对于这种情况,有必要进行 jQuery 方式绑定。
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/
这里小提琴例如 - http://jsfiddle.net/STEVER/5bfkbh7u/
采纳答案by dfsq
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 sameevent 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:
但是,您可以利用这样一个事实,即在控制器和指令中这是相同的事件对象ngClick
。所以你可以做的是为这个事件对象设置一些属性并在指令中检查它:
$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');
}
});
}
回答by James Gaunt
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.
您是否尝试过降低此指令的优先级以确保它在 ng-click 指令之后绑定?我假设事件按照它们被绑定的顺序触发,这又由 ng-click 指令与您的指令的优先级决定。
You also need stopImmediatePropagation to prevent any more handlers on the same element from firing. stopPropagation just prevents the event propagating to parent handlers.
您还需要 stopImmediatePropagation 以防止触发同一元素上的更多处理程序。stopPropagation 只是阻止事件传播到父处理程序。
回答by Manik Thakur
Use e.stopImmediatePropagation();
elem.bind('click', function (e) {
if (disable(scope)){
e.stopImmediatePropagation();
return false;
}
return true;
});
回答by A.B
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
这里没有任何事件传播,因为您有按钮,并且您必须在同一元素上进行事件,这不会发送到子元素的父元素,即这里没有事件冒泡或事件捕获