Angularjs and Requirejs and ANGULARAMD

Source: Internet
Author: User
Tags script tag

Recently because of the use of ANGULARJS development projects, because of the static resources involved more, so want to put the JS file through Requirejs to load on demand, both frameworks have been used before, but the combination has not been used, then try to see whether it can achieve the purpose.

Requirejs is to achieve the JS file asynchronous loading and management module between the dependencies of the framework, see Nanyi require.js usage and requirejs Chinese network here do not introduce.

Let's start by creating a template container index.html
<!DOCTYPE html>  

The only one JS file introduced is the Require.js file, this is the Requirejs core file, the script tag's properties Data-main used to specify the Requirejs of the portal file, the lower Div is Angularjs dom container, here because of the use of Angularjs , so you do not have to specify the Ng-app property on the Div.

Create a requirejs Portal file Main.js
(function(){    require.config({        baseUrl : "js",        paths : {            "jquery" : "jquery/jquery-1.12.2.min",            "angular" : "angular/angular",            "angular-route" : "angular/angular-route",            "domReady" : "require/domReady",            "controllerModel" : "controller/controller"        },        shim : {            "angular" : {                exports : "angular"            },            "angular-route" : {                deps : ["angular"],                exports : "angular-route"            }        },        deps : [‘app‘]    });})();
    1. The BASEURL is used to specify the directory where the module is loaded, and subsequent paths are relative paths to this directory.
    2. paths specifies the load path for the module.
    3. Shim Configuring incompatible Modules
    4. DEPS specifies a dependent module, Requirejs loads the file and executes it.

Our current file directory interface is this: JS file directory is like this

Create Angularjs execution File app.js

Next we will create the ANGULARJS module and configure the route and then manually trigger the ANGULARJS via the built-in method bootstrap. App.js files are dynamically loaded via Requirejs, so write them according to the AMD specification.

(function(){    define(["angular","angular-route","mainController",‘domReady!‘],function(angular){        //创建angularJS模块        var app = angular.module("webapp",[            ‘ngRoute‘,            ‘webapp.controllers‘        ]);        //设置angularJS路由        app.config(function($routeProvider,$locationProvider){            $routeProvider.when("/",{                templateUrl : "tpl/sy.html",                controller : "syCtrl"            }).when("/login",{                templateUrl : "tpl/login.html",                controller : "loginCtrl"            });            $locationProvider.html5Mode(false).hashPrefix("!");        });        //手动触发angularJS        angular.bootstrap(document,[‘webapp‘]);        return app;    });})();

App.js relies on the JS module has

    1. Angular Angularjs Core file
    2. Angular-route Angularjs Routing file
    3. domready! This is the Requirejs plugin that allows the callback function to run after the page DOM structure is loaded.
    4. Maincontroller This is the controller we're going to write next.
Creating templates

Before creating the controller we create the next template, according to the above route description, there are two pages one is sy.html, one is login.html, create the two templates, and put them in the TPL folder.
Sy.html

Login.html

Create a controller Maincontroller

In the App.js file, the Maincontroller module is loaded via Requirejs, and the Maincontroller module can be thought of as the controller's entrance, where all controllers are loaded asynchronously.

Following the route description rules, we need to create the Syctrl and Loginctrl controllers and add them to the Controller portal file maincontroller.js.

Maincontroller.js

(function(){    define([        ‘controller/syCtrl‘,        ‘controller/loginCtrl‘    ],function(){    });})();

Next we create the two controllers, Syctrl and Loginctrl, and before we create the two controllers, we'll look at how ANGULARJS creates the controller.

var angularController =  angular.module("angularController",[]);  angularController.controller("ctrlName",function(){  });

From the above code can be seen ANGULARJS controller is to create the angular module, and then execute the current module controller method to bind the controller, the new module created in the App.js file relies on injecting the current module Angularcontroller.

In the App.js file we specify that the dependent controller module is webapp.controllers. We need to create a file that is provided for all controller files to provide the Webapp.controller module while all the controllers are bound to the Webapp.controllers module, and then the controller can execute after setting the dependency injection in the App.js file. We create the Controller folder into the JS folder and create the following file:

The Controller.js file is the common file of the controller module we are creating, and the bottom two files are single controller files, all two of which depend on the modules provided by Controller.js.
The Controller.js name we configured in the Main.js file is Controllermodel so you can rely on Controllermodel directly if you need to rely on controller.js.

Controller.js

(function(){    define([‘angular‘], function (angular) {        return angular.module(‘webapp.controllers‘, []);    });})();

The Controllermodel module returns the created ANGULARJS module Webapp.controllers,app.js file and puts the dependency injection in the second parameter of the module method.

Next, we'll create the Syctrl.js and login.js files.

Syctrl.js

(function(){    define([‘controllerModel‘],function(controllers){        controllers.controller(‘syCtrl‘,function($scope,$location){            $scope.data = "我是sy";            $scope.goLogin = function(){                $location.path("/login")            }        })    })})();

Login.js

(function(){    define([‘controllerModel‘],function(controllers){        controllers.controller(‘loginCtrl‘,function($scope,$location){            $scope.data = "我是login";            $scope.goSy = function(){                $location.path("/")            }        })    })})();

Both controllers rely on Controllermodel, and then call the controller method of the Controllermodel module to create controllers, and the rest is to bind the data in the controller.

Looks like a mess.

After completing all of the above steps, the application is finally finished, and we look at the effect on the open page

This is what happens when you open the homepage.

Click on the login page to go to the login page and then click on the Sy page to jump to the SY page

function seems to be no problem, I want to load the implementation of on-demand? We look at the loading of the file, I need the function is to access the SY page when the Syctrl controller is called, access to the login page call Loginctrl controller. Unfortunately, in the home page when the controller is loaded, so the result is inevitable, because we load the controller through the Requirejs when the Maincontroller.js file is all the controller is loaded over. The Maincontroller.js module is loaded and executed only once when the WebApp module is created, so all controllers must be loaded and bound to the WebApp module.

My intention was to divide the controllers into separate files and then call when a controller needs to be loaded. In the actual development, involved in the module too many times we want to manage a separate module through a separate file, and then through the grunt and other tools online merged into a file in the production environment to use, so the merged file if very large will affect the page loading speed, if not merged, the number of requests will be too many, So by Requirejs to load each module asynchronously, what we did above is not meaningless, after all, we have solved the problem of loading the file too large.

ANGULARAMD for on-demand loading

We did a lot of work, but didn't solve the most fundamental problem-loading on demand. Next we need to solve this problem. We use another example to simply illustrate the ANGULARJS controller, on-demand loading of the service, on-demand loading of instructions I don't think it's necessary that the custom directives are mostly handled as public functions, So when you create a angular module, you specify that the Requirejs dependency is called directly on the line.

For more information, see Dynamic Load controller with ANGULARAMD and dynamic load service with ANGULARAMD

Installation
bower install angularAMD  bower install angular-ui-router  

Bower will automatically load the dependent JS file, all files are put into the Bower_components folder

Creating template files and JS entry files

Index.html

<!DOCTYPE html>  

The template file is the same as the template file you created last time, with the Requirejs portal file to handle the next work.
Main.js

(function(){ require.config({ paths: { "angular": "bower_components/angular/angular", "angular-ui-router": "bower_components/angular-ui-router/release/angular-ui-router", "angularAMD": "bower_components/angularAMD/angularAMD", "ngload": "bower_components/angularAMD/ngload" }, shim: { "angular": { exports: "angular" }, "angular-ui-router": ["angular"], "angularAMD": ["angular"], "ngload": ["angularAMD"] }, deps : ["app"] });})();

The content of the Main.js file is the same as before, the URL of each module is configured, and the dependent module App.js file is specified, and app.js is the portal to create the Angularjs module.

Next we create the App.js file

App.js

(function () {define (["Angular", "angularamd", "angular-ui-router"], function (angular, ANGULARAMD) {//Set route             var registerroutes = function ($stateProvider, $urlRouterProvider) {$urlRouterProvider. Otherwise ("/home");  $stateProvider//home State ("Home", Angularamd.route ({URL:                "/Home", Templateurl: "home.html", Controllerurl: "Home.js"}))                    Home state ("about", Angularamd.route ({url: "/about",                   Templateurl: "About.html", Controllerurl: "About.js"});                };        Instantiate angularjs var app = Angular.module ("app", ["Ui.router"]);        Configure App. Config (["$stateProvider", "$urlRouterProvider", RegisterRoutes]);    Manually start Angularjs and return the Angularjs instance object return Angularamd.bootstrap (APP); });}) (); 

The App.js file we created here is the same as the App.js file described earlier, and the only difference is the change in the content of the dependent module, which is also different when using the corresponding module, but the function is the same.

At the same time, it is important to note that when configuring routing, you should not only specify ur and template URLs, but also specify the corresponding controller URLs for each template.

Yes, this simple configuration will allow the controller to load on demand. We visit the home page Angularjs will automatically load the home.html template and Home.js controller, after loading the completion of the execution mode and the same as the front.

Add template files home.html and controller files home.js

Home.html

Home.js

(function(){ define([], function () { return ["$scope", function ($scope) { $scope.title = "This is Home page"; }]; });})();

Home.js is the home controller, you can see the method of the SY controller, the login controller is different, first through the Requriejs to determine the dependency module, and then return the array in the callback function, the last element of the array is the controller's execution function, The front is the controller needs to load the service, in fact, the return value is to create a controller function controllers of the second parameter, the first parameter is the controller name, this should be automatically specified internally.

So our first route is created, access the page

Add the About template file about.html and controller About.js

About.html

About.js

(function(){ define([], function () { return ["$scope", function ($scope) { $scope.title = "This is About page"; $scope.user = "tudou"; }]; }); })();

About.js and html.js content, do not explain.

The controller loads on demand

Access to the home Page JS resource load situation as follows the previous file is dependent on the module load, Home.js and home.html is the current page needs template and resources, not loaded about the content of the page, we click the button to go to the About page to see. You can see a new load of two files on the About page about.js and about.html
Our controller's on-demand load implementation, next we want to implement the service load on demand

Service load on Demand

Create a service userrepository.js file

(function(){    define(["app"],function(app){        app.factory("UserRepository", function(){            return {name:"tudou"};        });    });})();

The creation of the service relies on the Angularjs module, which is in controller/ Controller.js created a ANGULARJS module specifically for the controller, this time we directly call App.js return ANGULARJS module, the same principle as mentioned above. The factory method of executing the module declares a service, and the service is generated.

Invoke Service

In fact, we have called the $scope service when we created the About.js and home.js, but the $scope service is the ANGULARJS built-in service, so we need to load the file before invoking the custom service, and then we can use it directly when the service that declares the call is passed to the controller. In the first parameter of the Define method, declare the dependent JS file, in the array returned by the callback function declaration service, about.js modified into the code below

(function(){    define(["UserRepository"], function (UserRepository) {        return ["$scope", "UserRepository",function ($scope,UserRepository) {            $scope.title = "This is About page";            console.log(UserRepository);            $scope.user = UserRepository;        }];     }); })();

This completes the on-demand loading of our ANGULARJS controllers and services. And the modularity of the filter should be the same as the service.

Angularjs and Requirejs and ANGULARAMD

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.