There are three ways an object can gain control over a dependent object:
1. Create dependent objects internally
2. Referencing this dependent object through a global variable
3. Passing parameters (in this case through the function parameters)
ANGULARJS manages the query and instantiation of dependencies through the $injector injector service, and obtains an instance of the dependent service through its Get method, which, in short, is the factory that produces the dependent objects, and is responsible for instantiating all the components in the ANGULARJS, including the application's modules, instructions, Controller.
Dependency injection can be done in three ways:
Inference-dependent injection
Angularjs infers that the name of the parameter is the dependent object.
Declarative Dependency Injection
The $inject property is explicitly declared as an array whose elements are the names of the dependent instance objects, and the order is consistent with the order of the parameters of the injected target.
In-line Dependency injection
When a Angularjs object is defined, it is passed directly to an array of arguments, and the preceding elements are the dependent names that can be injected into the object, and the last element is the target object itself.
To summarize, when any module starts, it should get an instance of the injector, which maintains a register list, and uses its has () method to determine whether a dependent object exists and gets it through the Get () method.
When we define controllers, directives, and modules, these objects should be added to the registry maintained by the injector (like a Dictionary object).
$injector API
- Annotate () helps $injector determine which services are injected into a function call and returns an object that consists of a service name.
- Get () Gets an instance of a dependent object
- The has () injector maintains a registry in which the required dependent objects exist.
- Instantiate (Type,locals) creates an instance of a JavaScript type, invokes its constructor with the new action symbol, and passes all arguments to the constructor, returning a new instance of type.
- Invoke (Fn,self,locals) FN to invoke the function, self is used to specify the this parameter of the calling method, locals passes additional arguments to enter.
Code test:
<!doctype html>
Note: When getting the injector, get the injector for the specified app, otherwise you won't find the dependent object you want.
The results of the operation are as follows:
AngularJs Study Notes (iii) Dependency Injection