One object usually has three ways to gain control over its dependencies:
- Create dependencies internally;
- Reference is made through global variables;
- Pass through parameters where needed
Dependency injection is done in a third way. Like what:
function SomeClass (greeter) {
this.greeter = greeter;
}
SomeClass.prototype.greetName = function (name) {
this.greeter.greet (name);
SomeClass can access internal greeter at run time, but it doesn't care about getting references to greeter.
To obtain a reference to a greeter instance, the creator of the SomeClass is responsible for constructing its dependencies and passing them in.
For these reasons, Angularjs uses the $injetor (injector service) to manage dependency queries and instantiations.
In fact, the $injetor is responsible for instantiating all the components in the ANGULARJS, including the applied modules, directives, and controllers.
For example, the following code. This is a simple application that declares a module and a controller:
Angular.module (' myApp ', [])
. Factory (' Greeter ', function () {return
{
greet:function (msg) {alert (msg );}
}
})
. Controller (' Mycontroller ',
function ($scope, greeter) {
$scope. SayHello = function () {
Greeter.greet ( "hello!");
};
When Angularjs instantiates the module, it looks up the greeter and automatically passes the reference to it:
<div ng-app= "myApp" >
<div ng-controller= "Mycontroller" >
<button ng-click= "SayHello ()" > hello</button>
</div>
</div>
Internally, the ANGULARJS process is the following:
Use the injector load
to apply var injector = Angular.injector ([' ng ', ' myApp ']);
Load $controller service via injector: var $controller = injector.get (' $controller ');
var scope = Injector.get (' $rootScope '). $new ();
Load the controller and pass in a scope, as ANGULARJS does at run time
var mycontroller = $controller (' Mycontroller ', {$scope: scope})
The above is the entire content of this article, I hope this article for everyone to learn angularjs dependency injection to help.