Home > Web Front-end > JS Tutorial > Detailed explanation of dependency injection in Angularjs_AngularJS

Detailed explanation of dependency injection in Angularjs_AngularJS

WBOY
Release: 2016-05-16 15:11:11
Original
1354 people have browsed it

There are usually three ways for an object to gain control over its dependencies:

  • Create dependencies internally;
  • Referenced through global variables;
  • Pass parameters where needed

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);
};
Copy after login

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!");
};
});
Copy after login

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>
Copy after login

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})
Copy after login

The above is the entire content of this article. I hope this article will be helpful to everyone learning Angularjs dependency injection.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template