MattDionis
MattDionis

Reputation: 3616

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);
      });
    }
  }
}

Upvotes: 4

Views: 4528

Answers (2)

Oleksandr V. Kukliuk
Oleksandr V. Kukliuk

Reputation: 211

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();
  }
}

Upvotes: 1

MattDionis
MattDionis

Reputation: 3616

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);
      });
    }
  }
}

Upvotes: 6

Related Questions