Skip to content

Instantly share code, notes, and snippets.

@mlynch
Last active July 31, 2017 14:37
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlynch/9bec29848b88792f27de to your computer and use it in GitHub Desktop.
Save mlynch/9bec29848b88792f27de to your computer and use it in GitHub Desktop.
Making of an AngularJS Directive

A while back I made a quick AngularJS directive for Bootstrap 3 Tooltips. I wanted to be able to specify tooltips on any element like this:

<button title="Settings" data-placement="bottom" data-delay="500"
data-toggle="tooltip"><i class="icon ion-gear"></i></button>

But I wanted to be able to do it without having to call $([data-toggle="tooltip"]').tooltip() every time I loaded a new page with tooltips, which is what you'd have to do if you were using vanilla jQuery and Bootstrap without something like Angular.

I built a really simple directive that worked perfectly, and I realized this was a perfect example of creating a simple custom directive that makes your life so much easier.

The Directive

To start, we need to figure out what kind of directive we would use for this. Since it's not a "component," we should avoid using an element directive. For this case, an attribute is what we want because it's more of a reusable "behavior."

Figuring out the name of the directive is actually really important and can save you a ton of time if you do it right. In this case I identified that all elements with tooltips had the title attribute on it, and figured that would be the best name for the directive:

angular.module('myApp')

.directive('title', [function() {
  return {
    restrict: 'A',
    link: function($scope, $element, $attr) {
      $element.tooltip();
    }
  }
}]);

And that's it. The great thing about this is it will work for any dynamic AngularJS content that is compiled and linked in the page. That means if you use it with your routing system, it will all Just Work. No more hacking jQuery calls to initialize tooltips, this happens for free!

And because the tooltip() function grabs settings from the attributes specified on the element, that means all of our Bootstrap Tooltip settings like data-delay also Just Work, which is just a wonderful addition!

So next time you see yourself doing something over and over again with an element, try creating a directive. With just a little bit of a work you can save yourself a ton of time, and maybe even have more fun.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment