Search code examples
angularjsangularjs-directiveangularjs-factory

Angular - create multiple directives from same function


To create a directive/controller/factory whatever, you provide a function serving as the "injection point":

angular.module('myApp').directive('myDirective', ['dependencies', function injectionPoint(dependencies) {}]);

Can you provide that injectionPoint via another function registered with Angular? e.g. a factory? I should note that I've declared everything in separate files, and I'm trying to do it 'the angular way' and not create unnecessary globals.

Specifically, I've got two input directives that are basically the same, just with different templates and isolate scope declaration.

I thought to create a "directive factory" I could use, like:

function directiveFactory(scopeOverride, extraInit) {
    return function directiveInjectionPoint(depedencies) {
        return { restrict...,
                 template...,
                 scope: angular.extend({/*defaults*/}, scopeOverride),
                 link: function(...) {
                           // default stuff
                           if(angular.isDefined(extraInit)) extraInit($scope, el, attrs);
                       }
    }
}

which I would then use like:

angular.module('myApp')
    .directive('myDirective1', directiveFactory({/* new stuff */))
    .directive('myDirective2', directiveFactory({/* other stuff */, fn2...));

But how do I register that function with Angular, and then use it in the directive declaration?


Solution

  • You can use a service and directives like this:

    app.factory('MyService', function() {
    
      var MyService = {};
    
      MyService.createDirective = function(scopeOverride, extraInit) {
        return {
          restrict: 'E',
          transclude: true,
          scope: scopeOverride,
          template: '<pre ng-transclude></pre>'
        };
      };
    
      return MyService;
    
    });
    
    
    app.directive('drzausDirective1', function(MyService) {
      return MyService.createDirective(true);
    });
    
    
    app.directive('drzausDirective2', function(MyService) {
      return MyService.createDirective(false);
    });
    

    http://plnkr.co/edit/BuKMXxMQ4XVlsykfrDlk?p=preview

    enter image description here