ANGULARJS Study notes--dependency injection (DI, Dependency injection)

Source: Internet
Author: User

Original address: Http://code.angularjs.org/1.0.2/docs/guide/di

First, Dependency injection (Dependency injection)

Dependency Injection (DI) is a software design pattern that handles how code obtains the resources it relies on.

For a deeper discussion of Di, you can visit Dependency injection (http://en.wikipedia.org/wiki/Dependency_injection), inversion of Control (http ://martinfowler.com/articles/injection.html), you can also visit the Software design mode book.

1. Di in a nutshell (simply say di)

object or function, you can only get the resources they depend on in the following three ways:

1) You can create dependent resources with the new operator.

2) You can find dependent resources through global variables.

3) The dependent resource can be passed in by parameter.

1, 22 ways are not optimal, because they are hard code for dependencies, which makes it not impossible to modify dependencies, but it becomes more complex. This is especially a problem for testing, which is often expected to provide a dependent resource for impersonation when testing independently.

The 3rd approach is relatively best because it removes the responsibility to position dependencies from the component (component). Dependency is only given to the component.

function SomeClass (greeter) {     This.greeter = greeter}someclass.prototype.dosomething = function (name) {     This.greeter.greet (name);}
In the above example, SomeClass does not care about locating greeter This dependency, it only passes greeter at run time.

This is more appropriate, but it will be the responsibility to get the resources to rely on the code that is responsible for building someclass there.

To manage the responsibility of creating dependencies, each angular application has a injector (http://code.angularjs.org/1.0.2/docs/api/angular.injector). Injector is a service locator that is responsible for locating and creating dependent resources.

The request dependency solves the hard code problem, but it means that the injector needs to run through the application. Passing injector will break law of Demeter (http://baike.baidu.com/view/823220.htm). In order to rectify this problem, we will rely on the responsibility of finding to injector.

The above said so much, look at the following I have modified the example, combined with the original text of the two examples, respectively, in the angular inside and outside the use of inject:

<! DOCTYPE html> 

Note that because of the Ng-controller, the Mycontroller is initialized, and it can satisfy all of Mycontroller's dependency needs, so that Mycontroller does not need to know the existence of injector. This is one of the best results. The application code simply requests the dependencies it needs and does not need to process the injector. This setting does not break the law of Demeter.

Second, Dependency Annotation (depending on the comment, the way to describe the dependency)

How does injector know what services need to be injected?

Application developers need to provide commented information that is injector used to resolve dependencies. All angular existing API functions refer to injector, as is the API mentioned in each document. The following is a three equivalent method of annotating our code with the service name information.

1. Inferring Dependencies (implied dependency)

This is the simplest way to get a dependency on a resource, but you need to assume that the parameter name of the function matches the name of the dependent resource.

function Mycontroller ($scope, greeter) {     ...}
Injector of the function, you can guess the name of the service to be injected (functionname.tostring (), REGEXP) by examining the function definition and extracting the function name. In the example above, $scope and Greeter are two services that need to be injected into the function (the name is also the same).

While this is simple, this method does not work when JavaScript confuses compression, because parameter names are changed. This makes this way only useful for pretotyping (product usability prototyping test, http://www.pretotyping.org/,http://tech.qq.com/a/20120217/000320.htm) and demo applications.

2. $inject Annotation ($inject notes)

In order to allow script compression to rename a function, the correct service is still injected, and the function must comment on the dependency through the $inject property. The $inject property is an array of the names of the services that need to be injected.

var mycontroller = function (Renamed$scope, renamedgreeter) {     ...} The stuff here depends, if it's not in the current module, it's still not known.
You need to rely on the corresponding module in the current module first. Similar to the previous example. But I don't know if this is the right way. Mycontroller. $inject = [' $scope ', ' greeter '];
It is necessary to be careful that the order of the $inject needs to be consistent with the order of the arguments of the function declaration.

This annotation method is useful for a controller declaration because it specifies annotation information along with the function.

3. Inline Annotation (in-line comment)

Sometimes it is inconvenient to use $inject annotations, such as when commenting directive.

For example:

Somemodule.factory (' greeter ', function ($window) {    ...;});
Because a temporary variable is required (to prevent it from being used after compression), the code expands to:
var greeterfactory = function (Renamed$window) {    ...;}; Greeterfactory. $inject = [' $window '];somemodule.factory (' greeter ', greeterfactory);

Because of this (code bloat), angular also provides a third style of annotation:

Somemodule.factory (' greeter ', [' $window ', function (Renamed$window) {     ...;}]);
Remember that all annotation styles are equivalent and can be used anywhere in a angular that supports injection.

Third, Where can I user DI?

Di spreads throughout the angular. It is usually used in the controller and factory methods.

1. DI in Controllers

A controller is a class that is responsible for (describing) the behavior of the application. The recommended controller declaration methods are:

var mycontroller = function (Dep1, DEP2) {     ...} Mycontroller. $inject = [' Dep1 ', ' dep2 ']; MyController.prototype.aMethod = function () {     ...}
2. Factory methods

The factory method is responsible for creating most angular objects. For example, Directive, service, filter. Factory method Registration in the module, the recommended factory declaration method is:

Angualar.module (' MyModule ', []).    Config ([' Depprovider ', function (depprovider) {    ...    }]).    Factory (' ServiceId ', [' Depservice ', function (depservice) {    ...    }]).    directive (' directivename ', [' Depservice ', function (depservice) {    ...    }]).    Filter (' FilterName ', [' Depservice ', function (depservice) {    ...    }]).    Run ([' Depservice ', function (depservice) {    ...}]);

ANGULARJS Study notes--dependency injection (DI, 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.