Create an AngularJS tooltip directive

Hi Guys,

I would like to share how I have implemented directive for tooltip.

index.html
<html ng-app="simpleDirective">
<head>
<script src="jquery.js"></script>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
 <div ng-controller="TooltipController">
  <div>
    <input type="text" ng-message-tooltip ng-custom-tooltip ng-message="first"/>
  </div>
  <div>
    <input type="text" ng-message-tooltip ng-custom-tooltip ng-message="second"/>
  </div>
 </div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', []);

app.controller("TooltipController", function($scope){
 $scope.first = "This is first text box"
 $scope.second = "This is second text box"
});

app.directive("ngMessageTooltip", function($window){
 return{
  restrict:"A",
  require:"ngCustomTooltip",
  link:function($scope, $element, attrs, notificationCtrl){
   $element.on("keydown", function(){
    notificationCtrl.showMessage($element)
   });
   
   $element.on("focus, blur", function(){
    notificationCtrl.hideTooltip();
   });
   
   angular.element($window).bind("resize", function(){
    notificationCtrl.showMessage($element);
   });
  } 
 }
});

app.directive("ngCustomTooltip", function(){
 return{
  restrict:"A",
  scope:{
   message:"=ngMessage"
  },
  controller:function($scope){
   this.showMessage = function($element){
    this.hideTooltip();
    var offset = $element.parent().offset();
    
var tooltip = "<div class='tooltip'><div class='tooltipNotch' style='top:"+(offset.top+14)+"px;left:"+(offset.left+20)+"px'></div>"+
       "<div class='tooltipBody' style='top:"+(offset.top+33)+"px;left:"+(offset.left)+"px'>"+$scope.message+"</div></div>";
    $("body").append(tooltip);
   };
   
   this.hideTooltip = function(){
    $(".tooltip").remove();
   }
  }
 }
});
Style
.tooltipNotch{
 position:absolute;
 border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 10px solid red;
    border-top: 10px solid transparent; 
}

.tooltipBody{
 position: absolute;
    border: 2px solid red;
    top: 41px;
    width: 10em;
    background: lightsalmon;
    border-radius: 5px;
    padding: 5px;
}

input[type="text"]{
 padding:5px;
 border-radius:5px;
 border:none;
 border:1px solid lightgrey;
 margin-bottom:10px;
 outline:none;
}


Good day :)

Post a Comment

0 Comments