Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
      });
    }
  }
}
like image 955
MattDionis Avatar asked Mar 15 '23 14:03

MattDionis


2 Answers

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);
      });
    }
  }
}
like image 103
MattDionis Avatar answered Mar 26 '23 18:03

MattDionis


Something like this can be used to extend the angular.element functionality:

angular.element.prototype.closest = function closest( selector )
{
  if( selector && selector.length )
  {
    var startChar = selector.substring( 0, 1 );
    switch( startChar )
    {
      case '.':
          return this.hasClass( selector.substring( 1, selector.length ) ) ? this : ( this.parent().length ? this.parent().closest( selector ) : this.parent() );
        break;

      case '#':
          return selector.substring( 1, selector.length ) == this[0].id ? this : ( this.parent().length ? this.parent().closest( selector ) : this.parent() );
        break;

      default: //tagname
          return ( this[0].tagName && selector.toLowerCase() == this[0].tagName.toLowerCase() ) ? this : ( this.parent().length ? this.parent().closest( selector ) : this.parent() );
        break;
    }
  }
  else
  {
    return this.parent();
  }
}
like image 21
Oleksandr V. Kukliuk Avatar answered Mar 26 '23 19:03

Oleksandr V. Kukliuk