1

I have some common functionality between a directive and a service. I'd really like to not copy the code between the two items. Is it possible to inject a service into a directive?

Ben
  • 60,438
  • 111
  • 314
  • 488
  • Good post about what can be injected: http://stackoverflow.com/questions/16828287/what-things-can-be-injected-into-others-in-angular-js – Dan Jun 08 '13 at 20:17

2 Answers2

2

Yes. In your directive simply do this:

.directive('directiveName', ['ServiceName', function(ServiceName) {
  return {
    link: function(...) {
      ServiceName.doSomething();
    }
  }
}]);
rtcherry
  • 4,840
  • 22
  • 27
1

Yeah, that's like one the main things services are for. You can inject to the outer function of your directive declaration:

myModule.directive('myDirective', function(awesomeService) {
  return {
    link: function(scope, element, attrs) {
      awesomeService.doSomethingAwesome();
    }
  };
});

Or, if your directive is using a controller, just inject it there:

var myDirectiveCtrl = function(awesomeService) {
  awesomeService.doSomethingAwesome();
};

myModule.directive('myDirective', function() {
  return {
    controller: myDirectiveCtrl,
    require: 'myDirectiveCtrl',
    link: function(scope, element, attrs, ctrl) {
      ctrl.doStuffMaybe();
    }
  };
});
jpsimons
  • 27,382
  • 3
  • 35
  • 45