AngularJS provides a powerful feature called Directive which let’s us extend the HTML functionality as per our own custom requirement. AngularJS provides a set of in built directives like ngBind, ngModel to name a few. In this tutorial, we’ll try to create angularjs directive which would show tool tip on any element it’s attached to using an attribute. The tutorial assumes the reader to have a basic knowledge of JavaScript, HTML and AngularJS.

Source code from this tutorial is available on GitHub.

Also read : How to Create a Simple AngularJS Data Grid Directive

Getting Started

We’ll make use of NPM to manage the dependencies. So, make sure you have Node.js installed in your system. Let’s start by initializing a new project using npm.

mkdir AngularToolTip 
npm init

Enter the required details and you should have your package.json file which would contain all dependencies that we’ll add through out this tutorial. Here is how the package.json file looks like:

{
    "name": "angular_tooltip_directive",
    "version": "1.0.0",
    "description": "AngularJS tooltip directive",
    "main": "app.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "repository": {
        "type": "git",
        "url": "git+https://github.com/jay3dec/AngularToolTipDirective.git"
    },
    "keywords": [
        "AngularJS"
    ],
    "author": "Jay",
    "license": "MIT",
    "bugs": {
        "url": "https://github.com/jay3dec/AngularToolTipDirective/issues"
    },
    "homepage": "https://github.com/jay3dec/AngularToolTipDirective#readme"
}

Download AngularJS using npm.

npm install angular@1.5.5 --save

The downloaded AngularJS library should be available in the node_modules folder. Create an index.html page where we’ll test our AngularJS directive. Create a app.js file where we’ll write our AngularJS code and include it in the index.html script reference.
Here is how the index.html page looks like:

Now that being done, let first design our HTML code and see how it would look like. I have already done that and here is the HTML code demo.

[codepen_embed height=”343” theme_id=”0” slug_hash=”oxKpLa” default_tab=”result” user=”jay3dec”]See the Pen oxKpLa by Jay (@jay3dec) on CodePen.[/codepen_embed]

We’ll try to convert the above code into a AngularJS directive which can be easily added as an attribute to other elements to show as tool tip.

Create AngularJS Directive

Inside the app.js file define the angular js module, controller and directive as shown:

angular.module('myApp', [])

.controller('myCtrl', function() {
    // body...
})

.directive('tooltip', function() {
    return {

    }
})

As seen in the above code we have defined an angular js module called myApp. We have a defined a controller function called myCtrl and we have defined our directive called tooltip. We want our directive to a attribute directive, so add the following option:

.directive('tooltip', function() {
    return {
        restrict: 'A'
    }
})

Copy the HTML code for the tool tip from our HTML demo and add it as template to the tool tip directive.

.directive('tooltip', function() {
    return {
        restrict: 'A',
        transclude: true,
        template: '

Inside the template HTML I have added an extra attribute ng-show to control the visibility of the tool tip on button click. It’ll become clear once we implement it. I have also added an option called transclude to the above directive.

What Does Transclude Do ?

Generally when we create a directive with a template, say for example, we have a directive called home which would display a template with paragraph

<p>You are in Home</p>

Now if you would call the above directive home as shown:

<div home>
    <p>Main Content</p>
</div>

It would replace the content Main Content and only display You are in Home. The transclude option prevents the directive from replacing the existing items. Inside the tooltip directive template we have a div with ng-transclude directive, which tells angular js to display the content inside the directive in the div with ng-transclude attribute.

Binding Click Event to AngularJS Directive

Next we need to attach a click event for the element on which directive attribute is used. On click we need to toggle the visibility of the tool tip. So, add a controller to the tool tip directive which would control the visibility of the tool tip.

angular.module('myApp', [])

.controller('myCtrl', function() {
    // body...
})

.directive('tooltip', function() {
    return {
        restrict: 'A',
        controller: function($scope, $element) {
            $scope.isShown = false;
            this.showHover = function() {
                $scope.isShown = $scope.isShown == true ? false : true;
            }
        },
        transclude: true,
        template: '<div ng-transclude></div>' +
            '<div id="divPopup" ng-show="isShown">' +
            '<div class="floatLeft">' +
            '<img src="images/tooltipArrow.png" />' +
            '</div>' +
            '<div class="floatLeft margin3">' +
            '<span>' +
            'I am the Hover Popup' +
            '</span>' +
            '</div>' +
            '</div>'
    }
})

As seen in the above code, we have added a controller to the tool tip directive. Inside the controller we have defined a function called showHover which would toggle the tool tip display using scope variable isShown. Next, we need to bind a click event to the element and call the controller showHover function to toggle the tool tip display. Add the link option to the directive to define the click event.

link: function(scope, element, attr, ctrl) {
    element.bind('click', function() {
        scope.$apply(function() {
            ctrl.showHover();
        });
    });
}

Inside the click event callback we have called the controller showHover function inside the scope.$apply to tell AngularJS that the scope variable isShown as been modified. Here is a demo of the above directive in action.

Wrapping It Up

In this tutorial, we saw how to create AngularJS directive for showing tool tip from the very scratch. In the coming tutorials, I’ll try to implement a couple of more features to the existing tool tip directive. Any suggestions or tutorial request are welcome. Do let us know your thoughts in the comments below.

Also read : Python REST API Authentication Using AngularJS