AngularJS - Dependency injection in services, factories, filters etc

JavascriptDependency InjectionAngularjs

Javascript Problem Overview


So I have some plugins and libraries I want to use in my angular app and (currently) I am simply referencing those functions/methods as they were intended in 99% of apps in a way that completely ignores dependency injection.

I have (for example) the javascript library "MomentJS" which deals with formatting and validating dates and I have uses for it throughout my app in controllers, services and filters. The way that I've learned (using AngularJS) is to create a service that references the function (and it's methods) and inject that service into my controllers, which works great.

The problem is that I really need to reference this library in all different kinds of components from services to filters to controllers and everything else. So, I guess my question is how do you do dependency injection in filters, services and everything else that isn't a controller?

Is this possible? Is this even beneficial?

Any help would be greatly appreciated :)

Javascript Solutions


Solution 1 - Javascript

Yes you can use dependency injection for filters and directives

Ex:

Filter:

app.filter('<filter>', ['$http', function(http){
    return function(data){
    }
}]);

Directive:

app.directive('<directive>', ['$http', function(http){
    return {
		....
    }
}]);

Service:

app.factory('<service>', ['$http', function(http) {
  var shinyNewServiceInstance;
  return shinyNewServiceInstance;
}]);

Solution 2 - Javascript

For the sake of completeness, here is a service example with injection:

app.service('<service>', ['$http', function($http) {
  this.foo = function() { ... }
}]);

Solution 3 - Javascript

While the already existing answers are correct and working, john papas angular style guide favors the use of the $inject service in Y091:

Filter:

app.filter('<filter>', MyFilter);
MyFilter.$inject = ['$http'];
function MyFilter() {
  return function(data) {
  }
}

Directive:

app.directive('<directive>', MyDirective);
MyDirective.$inject = ['$http'];
function MyDirective() {
  return {
    ...
  }
}

Factory:

app.factory('<factory>', MyFactory);
MyFactory.$inject = ['$http'];
function MyFactory() {
  var shinyNewServiceInstance;
  return shinyNewServiceInstance;
}

Service:

app.service('<service>', MyService);
MyService.$inject = ['$http'];
function MyService() {
  this.foo = foo;
  function foo(){
    ...
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin BealView Question on Stackoverflow
Solution 1 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 2 - Javascriptuser1338062View Answer on Stackoverflow
Solution 3 - JavascriptDanielView Answer on Stackoverflow