AngularJS - 多NG-点击 - 事件冒泡 [英] AngularJS - multiple ng-click - event bubbling
问题描述
在下面的例子:
<李NG重复=中的项项NG点击=showItem(项目)>
< H3> {{item.title}}< / H3 GT&;
<按钮NG点击=删除(项目)>删除< /按钮>
< /李>
当我点击按钮 showItem()
也因事件冒泡调用。
我知道,我可以使用 $事件
来观看 $ event.currentTarget
做 $ event.stopPropagation()
等,但是这是非常难看。
顺便说一句。我不想停在按钮传播
(在我的情况下,按钮
是 Twitter的引导
dopdown /按钮
- 这只是一个例子)
如何停止 showItem()
从当我点击删除
按钮beeing叫什么名字?
修改
丑陋的解决将是有:
函数删除(项目,$事件){
$ event.originalEvent prevent = TRUE。
//将code休息
}功能showItem(项目,$事件){
如果($ event.originalEvent prevent)返回;
//将code休息
}
该解决方案为我(我只支持最新的浏览器,所以我试图修改code更复古兼容):
HTML
<李NG重复=中的项项NG点击=showItem(项目)>
< H3> {{item.title}}< / H3 GT&;
<按钮NG点击=删除(项目,$事件)>删除< /按钮>
< /李>
脚本:
函数删除(项目,$事件){
//做一些code在这里 // prevent浮上showItem。
//在最新的浏览器,只需要$ event.stopPropagation()
如果(event.stopPropagation)$ event.stopPropagation();
如果($事件preventDefault)$事件preventDefault()。
$ event.cancelBubble = TRUE;
$ event.returnValue =虚假的;
}
功能showItem(项目){
// code在这里
}
修改 - 增加的jsfiddle演示尝试一下
http://jsfiddle.net/24e7mapp/1/
In the following example:
<li ng-repeat="item in items" ng-click="showItem(item)">
<h3>{{item.title}}</h3>
<button ng-click="remove(item)">Remove</button>
</li>
When I click on the button showItem()
also is invoked due to event bubbling.
I know that I can use $event
to watch for $event.currentTarget
and do $event.stopPropagation()
etc. but this is very ugly.
Btw. I don't want to stop propagation on the button
(In my case the button
is a twitter bootstrap
dopdown/button
- this is just an example)
How do I stop showItem()
from beeing called when I click on the remove
button?
EDIT The ugly fix would be to have:
function remove(item,$event){
$event.originalEvent.prevent = true;
// rest of the code
}
function showItem(item,$event){
if($event.originalEvent.prevent)return;
// rest of the code
}
This solution worked for me (I'm only supporting recent browsers, so I tried to modify the code to be more retro-compatible):
HTML:
<li ng-repeat="item in items" ng-click="showItem(item)">
<h3>{{item.title}}</h3>
<button ng-click="remove(item, $event)">Remove</button>
</li>
Scripts:
function remove(item, $event) {
// do some code here
// Prevent bubbling to showItem.
// On recent browsers, only $event.stopPropagation() is needed
if ($event.stopPropagation) $event.stopPropagation();
if ($event.preventDefault) $event.preventDefault();
$event.cancelBubble = true;
$event.returnValue = false;
}
function showItem(item) {
// code here
}
EDIT - Added a JSFiddle demo to try it out http://jsfiddle.net/24e7mapp/1/
这篇关于AngularJS - 多NG-点击 - 事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!