Using closures to generate multiple similar directives in Angular

Have you ever needed two Angular directives that happened to be almost identical except for some configuration variable or callback? Yes? Hot dog, have I got something for you! It's not the most unique thing ever done with a closure, but it is a slick trick that just might help you keep your code a little more DRY.

I ran across a scenario recently where I had two element directives with identical markup and link functions, other than one line of configuration. Rather than maintain two sets of nearly identical files, I combined them using a technique like the one demonstrated below or in this plunker. Instead of writing my directive as a function returning an directive object, I write a function that takes configuration as args and returns a function that returns the intended directive object. By executing the outer function and naming the directives uniquely, you can now produce multiple directives that share a common template and body of code from a single set of files.

(function() {
  angular.module('configurableDirectives', [])
    .directive('exponential', accelerationConfigurer('exponential'))
    .directive('linear', accelerationConfigurer('linear'));

  function accelerationConfigurer(accelerationType) {
    acceleration.$inject = [];

    return acceleration;

    function acceleration() {
      var directive = {
        restrict: 'E',
        scope: {},
        link: linkFunc
      };

      function linkFunc(scope, element) {
        element.append('<div>' + accelerationType + '</div>');
      }

      return directive;
    }
  }
})();

I attempted to cook up a version of this that was more functional using .bind(), but it doesn't seem to be compatible with Angular's dependency injection system. If you figure out a way to drop the "configurer" function and use .bind() to attach the configuration value without breaking DI, please comment below.

AngularJavaScriptquick tips