[英]How to prevent ng-click in container not be triggered by elements inside in AngularJS
I have this situation: 我有这种情况:
<div ng-click="foo()">
<a ng-click="bar()">Bar</a>
<p>Lorem Ipsun</p>
</div>
My problem is, when I click in Bar, foo() is called too. 我的问题是,当我单击Bar时,也会调用foo()。 How to call just bar() when click in Bar, and just call foo() when I am not click in bar()? 在单击Bar时如何仅调用bar(),而在不单击bar()时如何调用foo()?
I got my answer in this question: 我在这个问题上得到了答案:
AngularJS ng-click stopPropagation AngularJS ng-单击stopPropagation
Just need to change the HTML to this: 只需将HTML更改为此:
<div ng-click="foo()">
<a ng-click="bar(); $event.stopPropagation()">Bar</a>
<p>Lorem Ipsun</p>
</div>
ngClick
provides the event object in a $event
variable. ngClick
在$event
变量中提供事件对象。 You can call stopPropagation()
on it to stop the event from bubbling... 您可以在其上调用stopPropagation()
以阻止事件冒泡...
<div ng-click="foo()">
<a ng-click="bar($event)">Bar</a>
<p>Lorem Ipsun</p>
</div>
Controller 控制者
$scope.bar = function ($event) {
$event.stopPropagation();
};
Use event.stopPropation() or event.cancelBubble = true to prevent event bubbling Write this code inside the bar() method to prevent calling foo() (parent) method 使用event.stopPropation()或event.cancelBubble = true防止事件冒泡在bar()方法内编写此代码,以防止调用foo()(父)方法
event = event || window.event // cross-browser event
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
JS Fiddle: http://jsfiddle.net/55sfc/1/ JS小提琴: http : //jsfiddle.net/55sfc/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.