Detailed description of dependency injection in Angularjs, detailed description of angularjs Injection
An object can be controlled in three ways:
- Create dependency internally;
- Use global variables for reference;
- PASS Parameters as needed
Dependency injection is implemented in the third way. For example:
function SomeClass(greeter) {this.greeter = greeter;}SomeClass.prototype.greetName = function(name) {this.greeter.greet(name);};
SomeClass can access internal greeter at runtime, but it does not care about how to obtain reference to greeter.
To obtain reference to the greeter instance, the creator of SomeClass is responsible for constructing its dependency and passing it in.
For the preceding reasons, AngularJS uses $ injetor to manage dependency query and instantiation.
In fact, $ injetor is responsible for instantiating all components of AngularJS, including application modules, commands, 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 searches for greeter and naturally passes its reference to it:
<div ng-app="myApp"><div ng-controller="MyController"><button ng-click="sayHello()">Hello</button></div></div>
The internal processing process of AngularJS is as follows:
// Use the injector to load the application var injector = angular. injector (['ng ', 'myapp']); // load $ controller service through the injector: var $ controller = injector. get ('$ controller'); var scope = injector. get ('$ rootScope '). $ new (); // load the controller and input a scope. Same as AngularJS does at runtime, var MyController = $ controller ('mycontroller', {$ scope: scope })
The above is all the content of this article. I hope this article will help you learn about Angularjs dependency injection.
Articles you may be interested in:
- In-depth understanding of dependency injection in Javascript
- How to Implement dependency injection in JavaScript
- Detailed description of dependency injection in JavaScript
- Detailed description of the dependency injection mechanism in AngularJS
- Analysis of problems related to using dependency injection in Node. js and Solutions
- How to Use js to implement the idea of dependency injection and move the idea of backend framework to the front end
- AngularJs dynamic loading module and dependency Injection
- Explanation of four dependency injection methods in the Javascript technology Stack
- Summary of four dependency injection methods in the Javascript technology Stack