Aaron Aaron - 5 months ago 13
AngularJS Question

Get Element Containing Click Event

Im trying to use event deligation to determine which template will be used in my directive. The problem is I cannot figure out how to get the button element where the click event is bound. The event target can vary depending on where the mouse is when the user clicks. It can be either the span or the button tag. What is the best way to get the button element whether the target is the span or button without all kinds of crazy conditional code?

Also I cannot customize the directive because I am using Angular Material and I can't use jQuery.

HTML:

<button ng-click="main.authDialog($event)">
<span class="ng-scope">Sign Up</span>
<div class="md-ripple-container"></div>
</button>

Answer

event.currentTarget tells you the element on which the event was hooked, rather than the one on which it was triggered (event.target).

Example:

var myApp = angular.module('exModule', []);
myApp.controller('exController', function($scope) {
  $scope.main = {
    authDialog(e) {
      console.log("target", e.target);
      console.log("currentTarget", e.currentTarget);
    }
  };
});
<div ng-app="exModule" ng-controller="exController">
  <button ng-click="main.authDialog($event)">
    <span class="ng-scope">Sign Up</span>
    <div class="md-ripple-container"></div>
  </button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


Side note: That HTML is invalid, button elements cannot contain div elements.

Comments