Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Dependency injection in services, factories, filters etc

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 :)

like image 805
Kevin Beal Avatar asked Mar 17 '13 05:03

Kevin Beal


People also ask

Which components can be injected as dependency in AngularJS?

Which Component can be Injected as a Dependency In AngularJS? In Angular. JS, dependencies are injected by using an “injectable factory method” or “constructor function”. These components can be injected with “service” and “value” components as dependencies.

What is Dependency Injection in AngularJS?

Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.

What are services and factories in AngularJS?

factory() is a method that takes a name and function that are injected in the same way as in service. The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not.

Which components Cannot be injected as a dependency in AngularJS?

Note that you cannot inject "providers" into run blocks. The config method accepts a function, which can be injected with "providers" and "constants" as dependencies. Note that you cannot inject "services" or "values" into configuration.


1 Answers

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; }]); 
like image 179
Arun P Johny Avatar answered Oct 19 '22 02:10

Arun P Johny