Angularjs Study notes Dependency Injection

Source: Internet
Author: User
Tags chrome developer

Recently in the Angularjs authoritative guide, for a variety of reasons (mainly because I do not have money, good nasty have wood there ...). ), so I chose to download the electronic version of the Internet (because it does not have money, haha ...) ), the font is pretty clear, the overall effect is good. However, when I see the top left corner of the total page number, 479 pages .... 479....479 .... My little heart was penetrated one-second there are wood, ah, the upper body are petrified wood has ah, the kind of special want to learn but see the page number and don't want to learn the tangled mood than and girlfriend quarrel also complicated there is wood, I usually read the number of e-books are not more than 3 of the good felling! Hey, forgive me, I should read a few more Xinhua dictionary habits ...

But fortunately before reading the ebook, I have a little bit of foundation, before watching the video learning some, from two-way data binding to the service, and then to the command system, are more or less contact. And in a Web-based elective course assignment, through the front-end of the Angularjs and backstage Nodejs plus mongoose built a simple student class management system. Because there is no money, so can only put on GitHub, GitHub address: Student management system, welcome to fork Ha, the following into the topic ...

======================================= please call me gorgeous split-line =======================================

An object typically has three ways to gain control over its dependencies:
(1) Create dependencies internally;
(2) referencing by global variables;
(3) pass through the parameters where needed.
Dependency injection is implemented in the third way. The other two approaches can cause problems such as polluting the global scope, making isolation extremely difficult, and so on. Dependency Injection is a design pattern that removes hard-coded dependencies, which can change or even remove dependencies at run time.

The ability to modify dependencies at run time is ideal for testing because it allows us to create an isolated environment in which simulated objects can be used instead of real objects in a production environment in a test environment.

Functionally, dependency injection automatically finds dependencies in advance and notifies the dependent resources of the injected target so that the resources can be injected as soon as the target is needed.

When writing components that depend on other objects or libraries, we need to describe the dependencies between components. At run time, the injector creates a dependent instance and is responsible for passing it on to the dependent consumer.

1 //excellent examples from angular documentation2 functionSomeClass (greeter) {3  This. greeter =greeter;4 }5SomeClass.prototype.greetName =function(name) {6  This. Greeter.greet (name);7 };8 //Note that the sample code creates a controller on the global scope, which is not a good idea, just for illustrative purposes. 

SomeClass can access the internal greeter at run time, but it does not care how to get a reference to greeter. In order to obtain a reference to the Greeter instance, the creator of the SomeClass is responsible for constructing its dependencies and passing in.
For these reasons, Angularjs uses $injetor (injector service) to manage queries and instantiations of dependencies. In fact, $injetor is responsible for instantiating all of the components in the ANGULARJS, including the application's modules, instructions, and controllers.
At run time, when any module is started $injetor is responsible for instantiating and passing all the dependencies it needs.
For example, the following code. This is a simple application that declares a module and a controller:

1Angular.module (' myApp '), [])2. Factory (' Greeter ',function() {3 return {4Greetfunction(msg) {alert (msg);}5 }6 })7. Controller (' Mycontroller ',8 function($scope, greeter) {9$scope. SayHello =function() {TenGreeter.greet ("hello!"); One }; A});

When Angularjs instantiates this module, it looks for greeter and naturally passes the reference to it:

1 <div ng-app= "myApp" >2 <div ng-controller= "Mycontroller" >3 <button Ng-click= "SayHello ()" >Hello</button>4 </div>5 </div>

Internally, the ANGULARJS process is as follows:

1 //loading an app with an injector2 varInjector = Angular.injector ([' ng ', ' myApp ')]);3 //loading the $controller service via the injector4 var$controller = Injector.get (' $controller ');5 //load the controller and pass in a scope, as ANGULARJS does at run time6 varScope = Injector.get (' $rootScope '). $New();7 varMycontroller = $controller (' Mycontroller ', {$scope: scope});

The above code does not describe how to find greeter, but it does work properly because $injector will be responsible for finding and loading it for us.
Angularjs uses the annotate function to extract the list of parameters from the passed-in function during instantiation. Enter the following code in the Chrome developer tool to see the function:

> injector.annotate (function($q, greeter) {}) ["$q", "greeter"]

In any ANGULARJS application, there are $injector working, whether we know it or not. When you write a controller, if you do not use the [] tag or make an explicit declaration, $injector try to infer the dependency by the parameter name.

Inferred injection Declarations   

If there is no explicit declaration, ANGULARJS assumes that the parameter name is the dependent name. Therefore, it calls the ToString () method of the function object internally, parses and extracts the function argument list, and then injects the parameters into the object instance by $injector. The injection process is as follows:

Injector.invoke (function ($http, greeter) {});

Note that this procedure applies only to code that is not compressed and confusing, because ANGULARJS requires the original uncompressed parameter list to parse. With this process of inference based on the name of the parameter, the order of the parameters has no significant significance, because ANGULARJS will help us inject the attributes in the correct order.

Explicit injection declarations  

ANGULARJS provides an explicit way to explicitly define the dependencies that a function needs to use when it is invoked. This method declares dependencies, even if the source code is compressed and the parameter name changes. The ability to explicitly inject declarations can be implemented through the $inject property. The $inject property of a function object is an array, the type of the array element is a string, and their value is the name of the service that needs to be injected.
Here is the sample code:

1 varAcontrollerfactory =2 functionAcontroller ($scope, greeter) {3Console.log ("LOADED Controller", greeter);4 //... Controller5 };6Acontrollerfactory. $inject = [' $scope ', ' greeter '];//greeter Service7Console.log ("Greeter Service");8 }9 //the controller we applyTenAngular.module (' myApp '), []) One. Controller (' Mycontroller ', Acontrollerfactory) A. Factory (' Greeter ', greeterservice); - //get the injector and create a new scope - varInjector = Angular.injector ([' ng ', ' myApp ')]), theController = injector.get (' $controller '), -Rootscope = Injector.get (' $rootScope '), -NewScope = rootscope.$New(); - //Call Controller +Controller (' Mycontroller ', {$scope: NewScope});

For this declarative approach, the order of the parameters is very important, because the order of $inject array elements must correspond to the order one by one of the injected parameters. This declarative approach can be run in the compressed code, because the information about the declaration is already bound to the function itself.

in-line injection declarations

The last way that ANGULARJS provides an injection declaration is the inline injection declaration that can be used at any time. This approach is actually a syntactic sugar, which is exactly the same as the one that was injected by the $inject attribute, but allows us to pass parameters from within the line when the function is defined. In addition, it avoids the use of temporary variables during the definition process.
When defining an Angularjs object, the way in which it is declared allows us to pass directly to a parameter array instead of a function. The elements of the array are strings, which represent the dependent names that can be injected into the object, and the last parameter is the target function object of the dependency injection.
Examples are as follows:

1 angular.module (' myApp ')2function($scope, greeter) {3 }]);

Because you need to work with a list of strings, inline injection declarations can also work correctly in compressed code. It is usually used by parentheses and by declaring the [] symbol of an array.

Angularjs Study notes Dependency Injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.