MattDionis MattDionis - 6 months ago 264
AngularJS Question

How to access closest element in AngularJS (no jQuery)

How could I properly access the closest element, as the below jQuery code accomplishes, in Angular without using jQuery?

link: function (scope, element, attrs) {
function handler($event) {
if(!($event.target).closest(element).length) {
scope.$apply(function () {
$parse(attrs.clickOutside)(scope);
});
}
}
}

Answer

I ended up simply checking if the element contains $event.target. The key here is that you must access element[0] and not simply element:

link: function(scope, element, attrs) {
  function handler($event) {
    if (!element[0].contains($event.target))  {
      scope.$apply(function() {
        $parse(attrs.clickOutside)(scope);
      });
    }
  }
}