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);
});
}
}
}
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);
});
}
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With