ANGUALRJS+AMD Specification example (primarily using REQUIREJS)-for on-demand loading

Source: Internet
Author: User

1. Background notes

Recently, we have been studying ANGULARJS and AMD, common specifications and so on. But how to combine Angularjs effectively with AMD's modular organization is worth pondering.

I studied for some time, in order to consolidate the research results, deliberately wrote a demo, for reference only.

2, the use of technical points explained

Kendo: Mainly use kendo open source some components (because I have more research on kendo)

Angular:angular as the underlying framework (MVC, DI, data binding, page routing, related services, etc.)

REQUIREJS:AMD Module Loader

Bootstrap: Mainly uses some of the styles it provides

3. App App creation process

The app launch process is as follows

3.1 Bootstrap

Start the angular application manually by using angular, wait for the page all scripts to load complete, find the HTML specified node (default is the root node), call Api/angular.bootstrap to compile the template into an executable, data two-way binding application

Code as follows,

Angular.element (document). Ready (function() {                angular.bootstrap (angular.element ("# Incidenttest "), [' Incident.app.module '];            });

3.2 AMD modules depend on how they are implemented

Use the AMD specification to implement dependencies between modules (the loader uses Requirejs).

Here need to wordy two sentences, some third-party JS Library does not conform to the AMD specifications, such as Angularjs, fortunately, there are shim properties in Requirejs.config, support non-AMD module loading

The configuration code is as follows

require.config ({        //baseUrl: ',        paths: {            ' angular ': '). /.. /.. /node_modules/angular/angular ",            ' kendo ':". /.. /.. /node_modules/kendo/license-2.0/kendo.ui.core.min ",            ' jquery ':". /.. /.. /node_modules/jquery/jquery-1.9.1.min "         shim: {            ' angular ': {                deps: [' jquery ') ],                "angular"            },            ' kendo ': {                deps: [' jquery ', ' angular ']            }     }    });

The AMD module is defined as follows

define ([' Incidentappeal.module '],function(incidentappealmodule) {})

3.3 Angular module Dependent implementation mode

Use the dependency injection mechanism provided by ANGULARJS to manage all module dependencies

Code as follows,

// Create Ui.module    Angular.module ("Ui.module",        [            "Ui.grid",            ' ui.grid.pinning ',            ' Ui.grid.resizeColumns ',            ' ui.grid.saveState ',            ' kendo.directives '        ]);

3.4 Module Loading mode

Use the REQUIREJS framework for loading AMD and non-AMD modules

Code as follows,

function () {        //go to app        function  (angular) {        //...             });        })    })

Controller, instruction, service, filter implementation in the 3.5 angular module

Use the corresponding provider provided by the angular. Injected into the angular framework system, according to the resolve properties provided by Ui-router (if you do not understand resolve this attribute of the classmate, you can check it yourself) to implement the on-demand load function.

Each angular module provides an extensible register attribute (including controller, Directive, filter, factory, service) with the following code,

workspacemodule.register={                    controller: $controllerProvider. Register,                    directive:$ Compileprovider.directive,                    Filter: $filterProvider. Register,                    Factory: $provide. Factory,                    service:$ Provide.service                };

Implement your own registration in each individual controller, Directive, filter, factory, service. Code as follows,

WorkspaceModule.register.controller ("Workspace", Mycontroller);})

3.6 How to achieve internationalization

Installing Angular-translate with NPM

Angularjs internationalization module to provide international services, the other modules first rely on the internationalization module, configure the current module note file (. json), to achieve the internationalization of the current module. Code as follows,

Angular.module ("Incidentcommon.localization.module",        [        "Pascalprecht.translate",        ' Incidentcommon.routeconfig.module '    ]);
varIncidentcommonlocalizationmodule = Angular.module (' Incidentcommon.localization.module ')); Incidentcommonlocalizationmodule.config ([' $translateProvider ',        ' Constantrouteconfig '        ,function($translateProvider, constantrouteconfig) {$translateProvider. usestaticfile Sloader ({files:[{prefix:constantrouteconfig[' Translate '].prefix, suffix:constantrouteconfig[' Translate '].suffix}]}); $translateProvider. Preferredlanguage (constantrouteconfig[' Translate '].preferredlanguage);    }]); Incidentcommonlocalizationmodule.factory (' T ', [' $translate ',function($translate) {varTrans =function(key) {if(key) {return$translate. Instant (key); }            returnkey;        }; returnTrans;    }]); returnIncidentcommonlocalizationmodule;

4. UI

4.1 Single page application (Ui-router, state)

Single page mainly uses the Angular-ui-router technology, realizes in the Workspace.module.

Ui-router Resolve attribute, before view load, angular will first resolve as a dependency on the view, load each AMD module configured on demand, so that according to the user to browse the view of the action on demand to load each view needs to rely on, such as Controller,

Directive, factory, etc., the code is as follows,

Workspace.left ": Route.resolve (' workspace.left ');  routeconfigs[" Workspace.left "] ={};    routeconfigs["workspace.left"].controllerdeps = "";    routeconfigs["Workspace.left"].controller=["Workspace/workspace.content.controller"];    routeconfigs["Workspace.left"].url = "workspace/workspace.content.html";

4.2 How to use and introduce the interface library

The interface library uses Kendoui primarily, using the Kendo open source control kendo.ui.core.js. Also add some controls that kendo need to charge, such as Angular-ui (Ui-grid/ui-chart/ui-treeview)

Introduction, code as follows,

Angular.module ("Ui.module",        [            "Ui.grid",            ' ui.grid.pinning ',            ' Ui.grid.resizeColumns ',            ' ui.grid.saveState ',            ' kendo.directives '        ]);

4.3 Style control

CSS styles are introduced directly in HTML,

<!--CSS    --<link href= ". /.. /styles/bootstrap/bootstrap.min.css "rel=" stylesheet "/>   ...     <link href= ". /.. /styles/styles.css "rel=" stylesheet "/>

4.4 Form Validation

Html5/angular/kendo self-Bringing authentication method

5. Code Frame Structure diagram

The Code framework diagram is as follows (here is just one simple),

6, several key points explain

Introduction of 6.1 Module.management centralized module management

(1), in order to reduce between the next module due to the AMD module load order caused by the inter-module dependencies unnecessary problems (such as circular dependence, of course, there are other solutions to cyclic dependence)

  (2), reduce the number of AMD modules

(3), the ANGUALR module creation and dependency configuration in an AMD module for management, more clear.

6.2 Load on Demand with view as driver

  (1), in line with the traditional Web multi-page development ideas, each view management of their own JS module depends on

(2), Angular-ui-router provides a set of perfect injection mechanism, support dynamic loading

(3), the following page code is dependent on the view of the business to expand, these AMD modules will be more and more. But after entering the system, some of the infrequently used view generally do not operate, resulting in some of the module JS may never be used,

This does not need to download all the JS files to the client at once.

7. Defects

  1, the packaging support is not good.

In addition, you are welcome to make valuable comments!

Demo Code Address

... To be continued, the following will also introduce a ANGULAR+COMMONJS specification demo, relying on Webpack packaging to run

ANGUALRJS+AMD Specification example (primarily using REQUIREJS)-for on-demand loading

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.