Angularjs Dependency Injection (DI, dependency injection) _angularjs

Source: Internet
Author: User
Tags function definition

I. Dependency injection (Dependency injection)

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

For more in-depth 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 Book of software design patterns.

1. Di in a nutshell (Jane says DI)

object or function can only obtain the resources they depend on in the following three ways:

1 You can create dependent resources from the new operator.

2 It is possible to find dependent resources through global variables.

3 The dependent resources can be passed through the parameters.

1, 22, not best, because they hard code for dependencies, which makes it not impossible to modify dependencies, but becomes more complex. This is particularly problematic for testing, which is typically expected to provide a simulated dependency when testing independently.

The 3rd approach is relatively feasible because it removes responsibility for locating dependencies from the component (component). Reliance is only given to the component.

function SomeClass (greeter) {
   this.greeter = greeter
}

SomeClass.prototype.doSomething = function (name) {
   This.greeter.greet (name);


The above example, SomeClass does not care about locating greeter This dependency, it only passes greeter at runtime.

This is more appropriate, but it gives the responsibility for acquiring resources to the code responsible for building SomeClass.

In order 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 locates and creates dependent resources.

Request dependency solves the problem of hard code, but it means that injector needs to run through the application. Passing injector will destroy the Demeter (http://baike.baidu.com/view/823220.htm). To correct this problem, we transfer the responsibility of relying on lookup to injector.

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

<! DOCTYPE html>  

Note that, because there is ng-controller, initialization of the Mycontroller, it can meet mycontroller all dependent needs, so that mycontroller do not need to know the existence of injector. This is one of the best results. The application code simply requests the dependencies it needs without having to deal with injector. This setting will not break the Demeter.

Ii. Dependency Annotation (dependency annotation, description of the way of dependency)

How does injector know what services need to be injected?

Application developers need to provide annotation information that is injector used as a solution to dependencies. All angular already have API functions that refer to injector, which is the API mentioned in each document. Here are three equivalent ways to annotate our code with service name information.

1. Inferring dependencies (implied Reliance)

This is the easiest way to get a dependent resource, but you need to assume that the parameter name of the function is the same as the name of the dependent resource.

function Mycontroller ($scope, greeter) {
   ...
}

function, you can guess the name of the service that needs to be injected (functionname.tostring (), REGEXP) by examining the function definition and extracting the function name (injector). In the example above, $scope and Greeter are two services (consistent names) that need to be injected into a function.

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

2. $inject Annotation ($inject notes)

To allow script compression to rename a function, you can still inject the correct service, and the function must annotate the dependency by $inject attribute. The $inject property is an array of the names of the services that need to be injected.

var mycontroller = function (Renamed$scope, renamedgreeter) {

   ...

}
The things that depend here, if not in the current module, it is still not known.
You need to rely on the corresponding module first in the current module. Similar to the previous example. But I don't know if it's 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 parameters of the function declaration.

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

3. Inline Annotation (in-line comments)

Sometimes it's not convenient to use $inject annotations, such as commenting on directive.

For example:

Somemodule.factory (' greeter ', function ($window) {

  ...;

});

Because temporary variables are needed (preventing compression from being used), the code expands to:

var greeterfactory = function (Renamed$window) {
  ...;
};
Greeterfactory. $inject = [' $window '];
Somemodule.factory (' greeter ', greeterfactory);

As a result of this (code bloat), angular also offers a third annotation style:

Somemodule.factory (' greeter ', [' $window ', function (Renamed$window) {
   ...;
}]);

Remember that all annotation styles are equivalent and can be used anywhere in the angular that supports injection.

Three, Where can I user DI?

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

1. DI in Controllers

Controller is the class that is responsible for (describing) the behavior of the application. The suggested controller declaration method is:

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. such as directive, service, filter. The factory method is registered in module, and 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) {
  ...
}]);

The above is the Angularjs Dependency injection of the data collation follow-up to continue to add, thank you for your support of this site!

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.