ANGULARJS Learning notes rely on injection of detailed _ANGULARJS

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 annoying wood has ... , so I chose to download the electronic version of the Internet (because it does not pay, haha ...) , the font is quite clear, the overall effect is good. However, when I see the total page number in the upper left corner, 479 pages .... 479....479 ... my little heart has been penetrated one-second have wood have ah, the upper body is petrified wood has ah, the kind of special want to learn but see the page numbers do not want to learn the tangle of feelings than and girlfriend quarrel with the complex has wood, ah, I usually look at the number of e-books are not more than 3 of good cutting! Hey, forgive me, I should read more of the habits of the Xinhua dictionary ...

But fortunately, before reading E-books, I have a little bit of a foundation, before watching the video to learn some, from two-way data binding to services, and then to the command system, are somewhat contact. And in the course of a Web selective session, a simple student class management system is built through the front-end Angularjs and the backstage Nodejs plus mongoose. Because there is no money, so can only put in GitHub, GitHub address: Student management system, welcome to fork Ha, the following into the topic ...

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

One object usually has three ways to gain control over its dependencies:

(1) creating dependencies internally;
(2) Using global variables for reference;
(3) Pass the parameter to the place where need.

Dependency injection is done in a third way. The other two ways can cause problems, such as polluting the global scope, making isolation extremely difficult, and so on. Dependency Injection is a design pattern that eliminates the hard coding of dependencies so that you 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 where simulated objects can be used in a test environment to replace real objects in a production environment.

Functionally, dependency injection automatically finds dependencies in advance and informs the injected target of the resource being relied on so that 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 to the dependent consumer.

Excellent example
function SomeClass (greeter) {
this.greeter = greeter
from angular documents SomeClass.prototype.greetName = function (name) {
this.greeter.greet (name);
Note that the sample code creates a controller on the global scope, which is not a good idea, just for demonstration purposes.

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 $injetor (the injector service) to manage the query and instantiation of dependencies. In fact, the $injetor is responsible for instantiating all the components in the ANGULARJS, including the applied modules, directives, and controllers.

At run time, when any module starts $injetor will be instantiated and all the dependencies it needs are passed in.

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 ']);
Loading the $controller service via the injector
var $controller = injector.get (' $controller ');
Load the controller and pass in a scope, as ANGULARJS does at run time
var scope = injector.get (' $rootScope '). $new ();
var Mycontroller = $controller (' Mycontroller ', {$scope: scope});

The above code does not show how to find greeter, but it does work because $injector is responsible for finding and loading it for us.

Angularjs through the annotate function, the parameter list is extracted from the passed function when instantiated. You can view this function by entering the following code in the Chrome developer tool:

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

In any ANGULARJS application, there are $injector working, whether we know it or not. When writing a controller, if the [] tag is not used or an explicit declaration is made, $injector attempts to infer the dependency through the parameter name.

An inferred injection declaration

If there is no explicit declaration, ANGULARJS assumes that the parameter name is the name of the dependency. Therefore, it calls the ToString () method of the function object internally, analyzes and extracts the list of function arguments, 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 uncompressed and confusing code, because ANGULARJS requires the original uncompressed list of parameters for parsing. With this process of inference based on the parameter name, the order of the parameters has no significance, because ANGULARJS will help us to inject the attributes into the correct order.

Explicit injection Declaration

ANGULARJS provides an explicit way to explicitly define the dependencies that a function needs to use when invoked. Declaring dependencies through this method can work even if the source code is compressed and the parameter name changes. The ability to explicitly inject declarations can be implemented by $inject properties. 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:

var acontrollerfactory =
function Acontroller ($scope, greeter) {
console.log ("LOADED Controller", greeter);
...... Controller
};
Acontrollerfactory $inject = [' $scope ', ' greeter ']; Greeter Services
console.log ("greeter service");
}
We apply the controller
angular.module (' myApp ', [])
. Controller (' Mycontroller ', acontrollerfactory)
. Factory (' Greeter ', greeterservice);
Gets the injector and creates a new scope
var injector = angular.injector ([' ng ', ' myApp ']),
controller = injector.get (' $ Controller '),
rootscope = Injector.get (' $rootScope '),
newscope = Rootscope. $new ();
Call Controller
controller (' Mycontroller ', {$scope: Newscope});

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

In-line injection declaration

The last way that ANGULARJS provides an injection declaration is that it can be used at any time in an inline injection declaration. This is actually a syntactic sugar, which is exactly the same as the one mentioned earlier by injecting declarations through the $inject attribute, but allows us to pass arguments in from the line when the function is defined. In addition, it avoids the use of temporary variables during the definition process.

When defining a Angularjs object, the inline declaration allows us to pass directly into an array of arguments instead of a function. The elements of an array are strings that represent the names of dependencies that can be injected into an object, and the last parameter is the object of the target function that relies on injection.

Examples are as follows:

Angular.module (' myApp ')
. Controller (' Mycontroller ', [' $scope ', ' greeter ', function ($scope, greeter) {
}]);

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

The above Angularjs dependency injection is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Related Article

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.