1

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?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. And the trick for me was to use the appropriate injections -- only the factory needed the dependencies (like constants, $http, etc) and the directives themselves only needed the factory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.