Technical Article => Web => HTML

In contemporary web application development, many front-end frameworks have been used to accelerate the speed of development and circumvent browser compatibility issues. Among them, AngularJS and Bootstrap are two frequently used.

AngularJS is a MVC JavaScript framework developed by Google to provide easy synchronization between user view and data model. While Bootstrap is developed by Twitter and it eases the work of designing a simple and concise UI without much manual design work involved. In some web applications, both frameworks are used together.

Tooltip is a component provided by Bootstrap which offers a smooth feel of displaying tooltip while hovering on some elements on a page, for example on a button or on a link. Usually, to enable tooltip functionality, below attributes need to be added to an element。

data-toggle = "tooltip"

data-placement = "right" (Direction can be left, right, top, bottom)

title = "" (Text on tooltip)

For example, to display "Edit" on a button, below is the HTML code.

<button class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Edit" > EDIT </button>

And in JavaScript, initialize the tooltip with below code :

$('[data-toggle="tooltip"]').tooltip();

Now what if you want to achieve the same in ng-repeat elements while using AngularJS? If you just copy and paste above HTML code into the ng-repeat elements, you would be disappointed to see that the tooltip will not show up anymore. In this case, a new directive can be created to bring back the tooltip.

A directive extends the standard HTML capability with customized markers. This is one of the most important and powerful features of AngularJS. To add the tooltip capability to an AngularJS-initialized element, below directive can be created.

// ToolTipApp is the ng-app application in your web app ToolTipApp.directive('tooltip', function(){ return { restrict: 'A', link: function(scope, element, attrs){ $(element).hover(function(){ // on mouseenter $(element).tooltip('show'); }, function(){ // on mouseleave $(element).tooltip('hide'); }); } }; });

Then in the element you want to add the tooltip, you need to add an attribute tooltip. With this, AngularJS will adds the extended behavior you defined to the element.

<button class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Edit" tooltip> EDIT </button>

What the directive does is it will match all attributes with name tooltip and register the hover listener on the element containing this attribute. Now the tooltiip will just work as normal.