Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain please AngularJS $injector with a clear example [closed]

Tags:

angularjs

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.

like image 360
Mikalaj Murziankou Avatar asked May 11 '13 16:05

Mikalaj Murziankou


People also ask

What is $injector in AngularJS?

Overview. $injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules. The following always holds true: var $injector = angular.

Is AngularJS open source?

AngularJS is a discontinued free and open-source JavaScript-based web framework for developing single-page applications. It was maintained mainly by Google and a community of individuals and corporations.

Why we use $inject in AngularJS?

It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable. AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.

What AngularJS means?

It's used to bind model from your controller to view only. It will not update your controller model if you change this from your view. It means it's used to achieve one time binding. Example.


1 Answers

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.

like image 124
Mark Rajcok Avatar answered Sep 21 '22 07:09

Mark Rajcok