Using Dependency Injection
- Such components as services, directives, filters, and animations are defined through the factory method or constructor that can be injected. These components can be injected with "service" and "value" components as their dependencies;
- The controller defined by the constructor can inject any "service" and "value" as its dependence, and can inject special dependence;
- The
run
method accepts a function that can inject "service", "value" and "constant" as a dependency, and note that "providers" cannot be injected into the run
code block ;
- The
config
method accepts a function that can inject "provider" and "constant" components as a dependency, noting that "service" or "value" cannot be injected into the configuration item .
Factory method
Use the factory function to define a directive, service, or filter. The factory method registers a module. The following is the recommended way to declare the factory method:
Angular.module (' MyModule ', []). Factory (function(depservice) { // ... }]). directive (function(depservice) { // ... }]). Filter (function(depservice) { // ...}]);
Module Methods
by calling config
and the run
Method Specifies the function run configuration and run-time module. These functions are injection-dependent, just like the factory function above.
Angular.module (' MyModule ', []). config ([function(depprovider) { // ... }]). Run ([function(depservice) { // ...}]);
Controllers
A controller is a class or constructor that provides application behavior that supports declarative markup in a template. It is recommended to declare a controller using array notation:
function ($scope, DEP1, DEP2) { ... function () { ... } ...}]);
with the services, you can have many instances of the same type of controller in your application.
Furthermore, additional dependencies are also available in the controller:
$scope
: The controller is closely related to DOM elements so you can access scope. Other components like services can only access the $rootscope;
- Resolves: If the controller instantiation is part of the route, then any value resolution injection to the controller is available in the route section
Angular: Dependency Injection