Simple Angular.JS 1.3 directive for Bootstrap tooltip

This is a very simple Angular.js (1.3) directive to add a Bootstrap 3 tooltip to any component.

angular.module('angularBootstrapTooltipApp')
  .directive('angularTooltip', function () {
    return {
      restrict: 'A',
      replace: false,
      scope: {
        tooltipPlacement: '=?',
        tooltip: '='
      },
      compile: function compile( tElement, tAttributes ) {
        return function postLink( scope, element, attributes, controller ) {
          if (scope.tooltip !== '') {
            element.attr('data-toggle', 'tooltip');
            element.attr('data-placement', scope.tooltipPlacement || 'top');
            element.attr('title', scope.tooltip);
            element.tooltip();  
          }
          
          scope.$watch('tooltip', function(newVal) {
            if (!element.attr('data-toggle')) {
              element.attr('data-toggle', 'tooltip');
              element.attr('data-placement', scope.tooltipPlacement || 'top');
              element.attr('title', scope.tooltip);
              element.tooltip();  
            }
            element.attr('title', newVal);
            element.attr('data-original-title', newVal);
          });
        };
      }
    };
  });

A simple example:

<button type="button" 
    class="btn btn-default" 
    angular-tooltip
    tooltip-placement="bottom"
    tooltip="title">
{{title}}
</button>
<input type="text" ng-model="title"></input>

Whatever you type, the tooltip will always be up to date.
Screenshot from 2015-05-05 19:41:37

Comes with no guarantee, but feel free to use it wherever you need it.

Advertisements

One thought on “Simple Angular.JS 1.3 directive for Bootstrap tooltip

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s