paradite paradite - 5 months ago 28
AngularJS Question

Add click event to element, but not its children in angular

I know this can be done with jQuery as shown here: 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' );
});


But in angular,
this
keyword is not binded to the element when I use something like:

<div ng-dblclick="ctrl.doubleClickHandler($event)">
parent, event should fire here.
<div>child, event should not fire here.</div>
</div>


and in my controller:

this.doubleClickHandler = doubleClickHandler;
function doubleClickHandler(event) {
console.log(this); // this binds to controller
console.log(event);
}


The event fires, but I need to prevent it from firing when I click on the element's children.

I don't want to hardcode a check on the
event.target
based on class or attribute because it might change later. Is there anyway to achieve this within the HTML tag, or in JavaScript without hardcoding the element's class or attributes (similar to the technique of binding the
this
keyword in jQuery)?

Answer

You can compare target and currentTarget. The former is the clicked element and the latter is the element with the handler.

function doubleClickHandler(event) {
  if (event.target !== event.currentTarget) return;
  // do something
}