Created
November 12, 2014 14:15
-
-
Save enapupe/2fc17dd38da99dd1ec9e to your computer and use it in GitHub Desktop.
AngularJS tooltip directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module("myApp").directive("theTooltip", function($timeout, $sce){ | |
return { | |
restrict: "E", | |
template: "<tooltip-arrow arrow-top></tooltip-arrow><tooltip-content ng-bind-html=\"content\"></tooltip-content><tooltip-arrow></tooltip-arrow>", | |
link: function(scope, elem, attr){ | |
scope.$on("tooltip.show", function(undefined, newval){ | |
elem.css("visibility", "hidden"); | |
scope.content = $sce.trustAsHtml(newval.content); | |
// aplicamos o escopo para forçar a renderizacao do novo content | |
// no tooltip, e assim poder calcular o novo tamanho no próximo | |
// stack que foi queued via timeout; | |
scope.$apply(); | |
attr.$set("ariaHidden", false); | |
$timeout(function(){ | |
var halfElemWidth = newval.element.offsetWidth/2, | |
halfTtipWidth = elem[0].offsetWidth/2, | |
ttipHeight = elem[0].offsetHeight; | |
var finalLeft = newval.element.offsetLeft + (halfElemWidth - halfTtipWidth); | |
var finalTop = (newval.element.offsetTop - (ttipHeight + 4)); | |
// colisoes laterais: | |
if (finalLeft <= 0) { | |
finalLeft = 0; | |
elem.find("tooltip-arrow").css("margin-left", (newval.element.offsetLeft+halfElemWidth-6) + "px"); | |
} | |
if( (finalLeft+(halfTtipWidth * 2)) >= window.innerWidth){ | |
finalLeft = window.innerWidth - (halfTtipWidth * 2) - 20; | |
elem.find("tooltip-arrow").css("margin-left", ((newval.element.offsetLeft - finalLeft) + halfElemWidth - 6) + "px"); | |
} | |
// colisoes verticais: | |
if(window.scrollY >= (finalTop)){ | |
attr.$set("inverted", true); | |
finalTop = (newval.element.offsetTop + newval.element.offsetHeight + 4); | |
} | |
elem.css("top", finalTop + "px") | |
.css("left", finalLeft + "px") | |
.css("visibility", "visible"); | |
}); | |
}); | |
scope.$on("tooltip.hide", function(){ | |
// reseto os atributos do ttip | |
attr.$set("ariaHidden", true); | |
attr.$set("inverted", false); | |
elem.css("top", 0) | |
.css("left", 0) | |
.find("tooltip-arrow").css("margin-left", "auto"); | |
}); | |
} | |
}; | |
}); | |
angular.module("myApp").directive("tooltip", function($rootScope){ | |
return { | |
restrict: "A", | |
scope: { | |
"tooltipHide": "=" | |
}, | |
link: function(scope, elem, attr){ | |
elem.on("mouseenter", function(){ | |
if(!scope.tooltipHide){ | |
$rootScope.$broadcast("tooltip.show", {content: attr.tooltip || attr.title, element: elem[0]}); | |
} | |
}); | |
elem.on("mouseleave", function(){ | |
$rootScope.$broadcast("tooltip.hide"); | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment