我知道这可以通过jQuery完成,如下所示:How to have click event ONLY fire on parent DIV, not children?
$('.foobar').on('click', function(e) {
if (e.target !== this)
return;
alert( 'clicked the foobar' );
});
但是在角度方面,this
关键字在我使用类似的东西时没有绑定到元素:
<div ng-dblclick="ctrl.doubleClickHandler($event)">
parent, event should fire here.
<div>child, event should not fire here.</div>
</div>
并在我的控制器中:
this.doubleClickHandler = doubleClickHandler;
function doubleClickHandler(event) {
console.log(this); // this binds to controller
console.log(event);
}
事件触发,但是当我点击该元素的子项时,我需要阻止它被触发。
我不想基于类或属性对event.target
的检查进行硬编码,因为它可能会在以后更改。无论如何在HTML标记中实现这一点,或者在JavaScript中没有对元素的类或属性进行硬编码(类似于在jQuery中绑定this
关键字的技术)?
答案 0 :(得分:6)
您可以比较target
和currentTarget
。前者是被点击的元素,后者是带有处理程序的元素。
function doubleClickHandler(event) {
if (event.target !== event.currentTarget) return;
// do something
}
答案 1 :(得分:0)
我想你可以尝试这样的事情:
<div ng-dblclick="ctrl.doubleClickHandler($event) $event.stopPropagation()">
参考:What's the best way to cancel event propagation between nested ng-click calls?
答案 2 :(得分:0)
我在你的样本中使用jquery通过create directive更新答案。
var app = angular.module("app", []);
app.controller("controller", function ($scope) {
var ctrl = this;
ctrl.doubleClickHandler = function () {
alert("parent clicked")
}
});
app.directive("directiveName", function () {
return {
restrict: "A",
scope: {
click: "&"
},
link: function (scope, element, attr) {
element.on('click', function (e) {
if (e.target !== this) {
return;
} else {
scope.click()
}
});
}
}
})
.foobar span {
background: red;
}
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller as ctrl">
<head>
<title></title>
</head>
<body>
<div click="ctrl.doubleClickHandler()" directive-name class="foobar">
parent
<span>
child
</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
答案 3 :(得分:0)
如果你使用jquery
试试这个,
<div class="foobar"> .foobar (alert)
<span>child (no alert)</span>
</div>
$('.foobar').on('click', function(e) {
if (e.target !== this)
return;
$scope.myFunc(e);
});
$scope.myFunc = function(e) {
$scope.clicked = "Parent Cicked";
$scope.$apply();
};
肯定不会导致良好的程序化技能。因此,您可以使用angular
和JS
尝试以下示例
<div class="foobar" data-parent="true" ng-click="myFunc($event)"> .foobar (alert)
<span>child (no alert)</span>
</div>
// add data attribute as data-parent="true"
$scope.myFunc = function(e) {
if (! e.target.hasAttribute('data-parent'))
return;
$scope.clicked = "Parent Cicked";
};
//if clicked element has `data-parent` property do the things.