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?
Asked
Active
Viewed 503 times
2 Answers
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