How to access the closest element in AngularJS (without jQuery)

How can I access the closest element, as the jQuery code below does 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);
      });
    }
  }
}
+4
source share
2 answers

In the end, I just checked if the element contains $event.target. The key here is that you should access element[0], not just element:

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

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

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

Source: https://habr.com/ru/post/1610014/


All Articles