ANGULARJS Module Specific explanation

Source: Internet
Author: User

Modules are functional blocks that provide some special services. For example, localization module is responsible for text localization, validation module is responsible for data validation. In general, the service is within the module, and when we need a service, we instantiate the module first. The method of the module is then called.

But the angular module is not the same as the module we usually understand. The angular module only retains the service's declaration, the service instantiation is completed by the service injector, the service is left in the service injector after the instantiation, and the module is not related, which is why the service we use all comes from the injector.

Each call to the Angular.boostrap () method creates a new angular application and a new service injector, so. Each application has a corresponding service injector. Do not conflict with each other.

In angular, a module can be an object, a method (assuming an array, the last element of an array must be a method.) The preceding elements are the method's sequential name. The module properties and methods are later spoken. All belong to the module object defined by Angular.module (). Suppose the module is a method. is not required to be defined by Angular.module (), simply write to the dependent array (that is, the element that relies on the array can be a method). The module runs directly when it is loaded into the dependency relationship.

Note: Modules defined by the Angular.module () method are unique. It is assumed that repeated definitions overwrite the previous definition.

Angular module

The angular module is generated by the Angular.module (Name,requires, Configfn) method:

    • The number of references is the module name.
    • The reference requires represents an array of dependent modules.

      Assuming that the requires parameter is not set, the Angular.module (name) method is called to obtain the module, so assuming that the new module has no dependencies, the requires must be set to an empty array [];

    • The parameter configfn is a method or an array. Be responsible for configuring some of the modules during initialization. The assumption is an array. The last element must be a method.

The Configfn method is not run immediately when the Angular.module () is run, but when the module is first used, it is run by the injector call.

At the same time, check the this in the method CONFIGFN to see that this is pointing to window in the browser. Rather than module. Also, the method CONFIGFN only runs once, so the same angular module is not configured repeatedly.

The string in the parameter requires represents the dependent module name. The assumption is not a string. Must be a method (or an array-formatted method), then. This method represents a module.

module with the same name

The initialized angular module is stored in a cache object called modules, where key is the module name and value is the module object. So. Defines a module with the same name, equal to the module before overwriting.

Service Injection

As already mentioned, the angular module only retains the definition of the service, and now we can understand how the service is added to the injector.

Before you know the service injector. It is also necessary to understand that there is another concept, namely, service providers. In the angular called provider, almost all services (except $injector) are supplied by the service provider. Whether it is a service or a service provider. They are the only ones in angular, and service and service providers are a one-to-ones relationship. It is also because of this relationship that when we use the module service (), value () and other methods, we feel as if we are defining just the service, but in fact angular created one by one corresponding service providers for these services. The mechanism of the injector is that when we need a service, we first find the corresponding service provider according to the service name. The service provider then creates the appropriate service and returns.

So that's the whole process:

    1. A module defines a service, a service provider.
    2. The injector is loaded into the module according to the module dependency, and the whole service provider is instantiated.
    3. The application requires service, and the injector is looking for a service provider based on the service name. Service provider instantiation Service.

These are just theories. Now, from a code perspective, how angular is implemented.

Each of the angular modules has three arrays built in. Invokequeue save information on how to inject service providers and values; Configblocks Save the configuration information for the module. Runblocks Save the running information for this module.

When the module is used, the injector is based on the information in the Invokequeue. Instantiate the service provider, do some extra processing for the service provider based on the information in the Configblocks, and invoke the work required by the previous service provider to run the module in accordance with the information provided in the runblocks.


The angular module provides a number of methods to populate these three arrays, such as config (), run (), and so on. The elements of a three-tuple are also arrays. Detailed element formats are described later in this note.


Call Queue –invokequeue

The array elements are [' provider ', ' method ', arguments].

Example – Add a controller:

Angular.module (' Ngappdemo ', []). Controller (' Ngappdemocontroller ', function ($scope) {      $scope. a= 1;      $scope. B = 2;});

This code equals:

Invokequeue.push ([' $controllerProvider ', ' register ', [' Ngappdemocontroller ', function () {}]]);

Based on this information, the injector will call the Register method of $controllerprovider for a ngappdemocontroller.

Configure Queue –configblocks

The element format is [' $injector ', ' invoke ', arguments].

Run Queue –runblocks

The element requirement is a method, or an array. The last element of an array is a method.

Angular module Instance properties and Method properties requires

Represents a dependent array of modules. That is, the requires parameter of the Angular.module method.

Name

The name of the module.

_invokequeue, _configblocks, _runblocks

respectively corresponding Invokequeue, Configblocks, Runblocks.

Method

The following method of the module eventually returns the module instance itself, forming the run chain .

Animation ()

Calling this method means that the module will register an animation service in the $animateprovider.

Principle: Insert [' $animateProvider ', ' register ', arguments] at the tail of the invokequeue .

Config ()

Calling this method means appending a configuration method to the module.

Principle: Insert [' $injector ', ' invoke ', arguments] at the tail of the configblocks .

Constant ()

Calling this method means that the module will give the default $provider a constant.

Principle: Insert [' $provide ', ' constant ', arguments] at the invokequeue header .

Controller ()

Calling this method means that the module will register a controller in the $controllerprovider.

Principle: Insert [' $controllerProvider ', ' register ', arguments] at the tail of the invokequeue .

Directive ()

Calling this method means that the module will register an instruction in the $compileprovider.

Principle: Insert [' $compileProvider ', ' directive ', arguments] at the tail of Invokequeue .

Factory ()

Calling this method means that a service factory will be generated in this module (implicitly creating a service provider).

Principle: Insert [' $provide ', ' factory ', arguments] at the tail of Invokequeue .

Filter ()

Calling this method means that the module will register a filter in the $filterprovider.

Principle: Insert [' $filterProvider ', ' register ', arguments] at the tail of the invokequeue .

Provider ()

Calling this method means that the module will join a service provider.

Principle: Insert [' $provide ', ' provider ', arguments] at the tail of Invokequeue .

Run (block)

Calling this method means that the module will run a function block. A block can be a method, and it can be an array.

Principle: Insert block at invokequeue tail .

Service ()

Calling this method means that the module will register a service (implicitly creating a service provider).

Principle: Insert [' $provide ', ' service ', arguments] at the tail of the invokequeue .

Value ()

Calling this method means that the module will register a variable (implicitly creating a service provider).

Principle: Insert [' $provide ', ' value ', arguments] at the tail of the invokequeue .

Service Injector (Services Injector) & service provider (Provider)

In angular, a service can be an object, a method, or a constant value . The service is created by the service provider. The service provider is managed uniformly by the injector. When we need a service. The injector is responsible for finding the appropriate service provider based on the service name and then creating the service instance from the service provider's $get () production plant. So. The service provider must have a $get () method, which is a service to create a singleton factory.

Behind the principle: the providers and services in the injector are stored in the cache (respectively, corresponding Providercache and Instancecache) via a Map object, only the providers key is ServiceName + " Provider ", while the services key is servicename.

Service provider-provider

Provider is a service provider and must have a $get () method. The return value of the $get () is the actual service provider in the injector.

Injection device

The method of creating the injector is only called in the Bootstrap () method, that is, each angular applies a corresponding injector.

Injection process

The injector is created by the Angular.injector (Modulestoload, Isstrictdi) method. The Createinjector method is in fact the angular. The parameter modulestoload is an array, and the element format is one of the following:

    • ' Module ', the name of the block.
    • [' Service1 ', ' Service2 ', FN].
    • FN, the return value of the method must still be a method.

Method Angular.injector () runs the process:

1. Traverse Modulestoload. Find or generate the corresponding module according to ModuleName.

2. Call all the methods in the module INVOKEQUEUE. The goal of this step is to create the necessary services.

3. Call all the methods in the module Configblocks to configure the module with the existing service.

4. Call the injector's Invoke () method to run the module Runblocks all methods.

5. Return to the service injector instance.

Not all modules are objects, assuming the module itself is a method or an array (the last element must be a method). The last method of running this method, or array, is equivalent to entering the fourth step directly.

The relationship between injector and Bootstrap

The method of creating the injector was called in Angular.js only in the bootstrap () method. That is, each angular applies a corresponding injector.

Injector method

A $injector object is built into the Providercache and Instancecache, respectively, and is responsible for injecting the service provider into the module and injecting the service into the method.

Generally we just talk about the $injector object in Instancecache. Because Providercache and its $injector are private, they are used only in angular internal code.

For example, the service provider is injected when you run the module call queue, the method in the configuration queue, and when you call a method in the run queue, the service is injected.

$injector. Invoke (FN, self, locals, serviceName)

Run the method fn.

Locals is an optional parameter, which is an object that represents a local variable.

Self is the this in FN.

The last parameter, ServiceName, is an optional parameter that indicates in which service the FN method was called, used for error message display, and no processing logic.

$injector. Instantiate (Type, locals, ServiceName)

Assuming that the parameter type is a method, create an instance (created by the Object.create method) based on the prototype of type, assuming the type is an array. Use the prototype of the last element.

L The locals is when the type method's participation is present in the locals object. The value of Locals[arg] is again a parameter of type. Assume that there is no locals. is equivalent to calling get (Arg,servicename) to get the service as a new parameter.

The instantiation process can be summarized briefly as

Type.apply (Object.create (type.prototype), locals[argname]| | get (Argname, ServiceName)).

Note: The instantiation is not necessarily an object. It can also be a method.

The last parameter, ServiceName, is an optional parameter that indicates in which service the type was instantiated, used for error message display, and no processing logic.

$injector. Get (name, caller)

Gets a service instance from the injector.

The number of references is the name of the service. The parameter caller is also a string that indicates which method is called for the service and is used for the error message hint. There is no processing logic.

$injector. Annotate (Fn[,strictdi][,name])

Returns an array. The elements of an array are dependent services that the FN method needs to inject.

In strict mode, the method's dependency injection must be joined using the displayed annotations, that is, through FN. $injector can get dependency injection of this method.

The parameter name is optional and is used for error display, with no processing logic.

Method Annotate () can also accept an array, the last parameter of the array must be FN, and the preceding element is dependent.

$injector. has (name)

Checks whether the specified service exists in the injector.

Provider method

A $provider object is built into the providercache of the injector, which is the default service provider for the injector, $provider there are six fixed methods. The main purpose of these methods is to join other service providers for injectors.

Attention:

    • all of the following methods name the number of references does not need to be " Provider "End, as provider () method will add this suffix by default.

    • Either method does not infer the same name, so assume the same name, which overrides the former.

$provider. Provide (name, provider)

The parameter provider can be either a method or an array, or it can be an object.

L If it is a method, it is the provider constructor.

Invokes the instantiate () method of the injector to generate an provider instance. And the name key is stored in the Providercache of the injector.

L Suppose it's an array. The last one must be a provider constructor. The preceding is the parameter name of the constructor. The following principle and provider are the same as the method.

The assumption is that the provider has been instantiated, and it is only necessary to have the $get () method.

$provider. Factory (name, FACTORYFN, enforce)

Using $provider.provide () generally requires defining a provider class, assuming you do not want to define the provider class, but rather define the service factory directly. will be able to use this method.

Behind the principle: first generate an anonymous object, the $get property of this object is FACTORYFN (enforce is false), and then the anonymous object as the $provider.provide () method of the second parameter. So. FACTORYFN, in fact, is still bound to a provider.

$provider. Service (name, constructor)

Call the Injector.instantiate () method to generate the service instance using the parameter constructor, which is the name of the service.

As we all know, the service is provided by provider, what is this method? Principle: Angular first generates a FACTORYFN based on constructor, and then calls $provider.factory (name, FACTORYFN).

So, in fact, a provider is generated.

Example:

$provider. Service (' filter ', constructor)

equals the creation of a filter service instance. and a service provider named "Filterprovider" is saved in Providercache.

$provider. Value (name, value)

This method actually calls the Injector.factory (Name,valuefn (value), false) method implementation. So the fact is that it creates a service provider that simply provides a value.

$provider. Constant (name, value)

This method adds a property implementation directly to the Providercache.

$provider. Decorate (serviceName, DECORFN)

Change the old service, run the Decorfn method instead, and servciename the original service as a parameter. The parameter name is $delegate. Equivalent to a static proxy.

Behind the principle: first find provider according to Sevicename, and then change the $get attribute of provider.

Service instantiation

All services are managed by provider, with the exception of constant values, which are generally not created yet.

Understand all the methods of the injector. It should also be possible to see that there are only two methods: Get () and Invoke () the actual invocation of the service.

In fact, the instantiation of the service is actually completed in the Get () method of the injector. Invoke () invokes get () only when it is needed.

Angular built-in module Nglocale-localization module

Angular.module (' Nglocale ', []). Provider (' $locale ', $LocaleProvider);

The result is Invokequeue.push ([' $provide ', ' Provider ', [' $locale ', $LocaleProvider]]);

Ng

Angular.module (' ng ', [' Nglocale ']). config ([' $provide ', function () {}]);

The result is Configblocks.push ([' $injector ', ' invoke ', [' $provide ', function () {}]]).

Three fixed modules

For each application generated using bootstrap (element, modules, config), there are three fixed modules in the injector:

    • The first module is "ng".
    • The second module is [' $provider ', FN], which is used to store the element elements as variables in the $provider.

    • The third module is [' $compileProvider ', FN], and its role is to invoke $conpileProvider according to config.debuginfoenabled. Debuginfoenabled (True).

ANGULARJS Module Specific explanation

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.