Explain please AngularJS $injector with a clear example

Angularjs

Angularjs Problem Overview


Due to deficiency of official docs explanation on $injector (service) I have hard time understanding how it actually works. How many $injectors may be per application? When should I use it? How does $injector work? (and so on) Please provide me with a real world explanation and some JavaScript sandbox samples on it.

Angularjs Solutions


Solution 1 - Angularjs

There is one injector per Angular application. Normally you don't need to interact with it directly. The injector is key to making dependency injection work in Angular.

Module methods such as factory, service, directive, etc. register these items with the injector. When you inject something (e.g., a service into a controller), the injector will lookup and then instantiate the service (if it wasn't instantiated already -- if it was, it will return the already-instantiated object).

If for some reason you really needed to dynamically inject a service into, say, a controller, see https://stackoverflow.com/a/14418384/215945 for an example of how to do that. See also https://stackoverflow.com/a/14743553/215945.

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
QuestionMikalaj MurziankouView Question on Stackoverflow
Solution 1 - AngularjsMark RajcokView Answer on Stackoverflow