There are usually three ways for an object to gain control over its dependencies:
Dependency injection is implemented through the third way. For example:
function SomeClass(greeter) { this.greeter = greeter; } SomeClass.prototype.greetName = function(name) { this.greeter.greet(name); };
SomeClass can access the internal greeter at runtime, but it does not care about how to obtain a reference to greeter.
In order to obtain a reference to the greeter instance, the creator of SomeClass is responsible for constructing its dependencies and passing them in.
Based on the above reasons, AngularJS uses $injetor (injector service) to manage dependency query and instantiation.
In fact, $injetor is responsible for instantiating all components in AngularJS, including application 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 this module, it will look for greeter and naturally pass a reference to it:
<div ng-app="myApp"> <div ng-controller="MyController"> <button ng-click="sayHello()">Hello</button> </div> </div>
Internally, AngularJS’s processing process is as follows:
// 使用注入器加载应用 var injector = angular.injector(['ng', 'myApp']); // 通过注入器加载$controller服务:var $controller = injector.get('$controller'); var scope = injector.get('$rootScope').$new(); // 加载控制器并传入一个作用域,同AngularJS在运行时做的一样 var MyController = $controller('MyController', {$scope: scope})
The above is the entire content of this article. I hope this article will be helpful to everyone learning Angularjs dependency injection.