SoFunction
Updated on 2025-04-11

requirejs AngularJS combined with example analysis

introduction

Recently, a project wanted to use requirejs to implement the loading of angularjs js files on demand. I also found a lot of information online but they are not very complete, or they are not very detailed, so I summarized it myself. Friends in need can take a look. Without further ado, just upload the code.

1. The project directory of simple examples is as follows:

js folder

--controllerFolders
  --- 
  --- 
  ---
--directivesFolders
  ---
  ---
--
--
--
--
--

2. Home page

First of all, yours is as follows

   <!doctype html>
    <!-- <html xmlns:ng="//"  
   ng-app="webApp"> -->
   <htmls>
   <head> 
   <meta charset="utf-8"> 
   <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
  </head>
      <body>
    <!--otherhtmlcontent-->
       <script data-main="js/main" src="../lib/require/"></script>
      </script>
    </body>
</html>

On the home page, you only need to introduce the requireJs library file and specify the entry function, and use manual startup of the angularjs application, so you don’t need to add ng-app='webApp' to the home page.

3. Configuration

Define RequireJS configuration

({
urlArgs: "==version==",
waitSeconds: 0,
paths: {
'jquery': '../../plugins/jQuery/jQuery-2.1.',
'bootstrap': '../../lib/bootstrap/dist/js/',
'angular': '../../lib/angular/',
'angular-route': '../../lib/angular-route/',
'angular-animate': '../../lib/angular-animate/',
'angular-resource': '../../lib/angular-resource/',
'angular-growl': '../../lib/angular-growl-v2/build/',
'domReady': '../../lib/require/domReady',
'jquery-ui': '../../lib/jquery-ui/',
},
shim: {
'angular': {
exports: 'angular',
deps: ['jquery']
},
'bootstrap': {
deps: ['jquery']
},
'angular-route': {
deps: ['angular']
},
'angular-animate': {
deps: ['angular']
},
'angular-resource': {
deps: ['angular']
},
'angular-growl': {
deps: ['angular']
},
'slimscroll': {
deps: ['jquery']
},
'tools': {
deps: ['jquery']
},
'configs': {
deps: ['jquery']
},
},
deps: [
'index-app',
'tools',
'configs',
]
});
require([
 'app',
 'routes',
         // This is a method to import 'loader',
 //Note: This is not Twitter Bootstrap, but AngularJS bootstrap 'angular-bootstrap',
 //All controller, service, instructions and filter files created must be written here, and this content must be manually maintained 'controllers/controllers',
 'directives/directives',
       ],
   function(app, config, loader) {
 'use strict';
 ([
     '$routeProvider',
     '$locationProvider',
     '$controllerProvider',
     '$compileProvider',
     '$filterProvider',
     '$provide',
     "$httpProvider",
     'growlProvider',
     function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $httpProvider, growlProvider) {
          = $;
          = $;
          = $;
          = $;
          = $;
         (""+);
         if( != undefined) {
             (, function(route, path) {
                 $(path, {
                     templateUrl: ,
                     controller: ,
                     resolve: loader()
                 });
             });
         }
         if( != undefined) {
             $({
                 redirectTo: 
             });
         }
         ({
             success: 3000,
             error: 5000,
             warning: 5000,
             info: 5000
         });
         $ = true;
         $ = true;
         delete $['X-Requested-With'];
     }
 ]);
 return app;
 }
 );

So in general, what this file does is: load all files asynchronously by requirejs;

There are various dependency methods in the function.

4. Manually start the angularjs application

document

    //When the DOM structure is loaded, the file will start and continue to execute    define(['angular', 'domReady', 'app'], function(angular, domReady) {
    require(['domReady!'], function(document) {
        (document, ['app']);
       });
    });

Here we depend on and, let's see what these two files do separately

five,

Now let’s take a look at how we usually write angularjs application.

  var app = ("xxx",["xxx"]);
  ("foo",function($scope){});
  (...)

So it's like this

 define([
'angular',
'angular-route',
'angular-resource',
'angular-animate',
'angular-growl',
'angular-animate',
     。。。
 ], function(angular) {
'use strict';
return ('app', [
    'controllers',
    'directives',
    'angular-growl',
    'ngAnimate',
    'ngRoute',
     。。。
   ]);
});

6. Website routing settings

We use ng-router here. So ours should be like this, mainly used to define routes. Please check the relevant knowledge for ng-router configuration yourself. Let's skip it here.

   define([], function() {
return {
    defaultRoutePath: '/index',
    routes: {
        '/index': {
            templateUrl: 'tpls/',
            controller: 'indexCtr',
            dependencies: ['js/controllers/', 'js/directives/']
            //This is to import js files on demand        },
    }
};
});

Of course, there is also a loader file that contains the method we define on-demand loading;

define([], function() {
  return function(dependencies) {
// Return the resolve definition of the route,var definition = {
  // resolver is a function that returns a promise object;  resolver: ['$q', '$rootScope', function($q, $rootScope) {
    // Create a delayed execution promise object    var defered = $();
    // Scripts loaded using requirejs' require method    require(dependencies, function() {
      $rootScope.$apply(function() {
        // After loading the script, complete the promise object;        ();
      });
    });
    //Return the promise object that is delayed execution, route will wait for the promise object to complete    return ;
  }]
};
return definition;
  }
 });

7. Controller

First of all, we want to write this

 define(['angular'], function(angular) {
      'use strict';
          var controllers = ('controllers', []);
   ([ '$controllerProvider', function($controllerProvider) {
         = $;
}
  ]);
   = function(controllerName, options) {
        var attrs = [];
        var fun = null;
      if((options)) {
                attrs = (0,  - 1)
                fun = options[ - 1]
         } else {
            fun = options;
        }
        (controllerName, fun);
          if ( > 0)
            fun.$inject = attrs;
          }
    return controllers;
  });

It is mainly used to load each controller (all controllers will be loaded in this file), and there is no need to do anything else, because we can have many controller files to add according to specific needs.

This is our specific controller

  define(['controllers/controllers'], function(controllers) {
      'use strict';
  ('user_centerCtrl', ['$scope', '$location', '$routeParams', '$timeout', '$http',
    function($scope, $location, $routeParams, $timeout, $http) {
        }
    ]);
 });

8. Instructions

The same is true.

define(['angular'], function(angular) {
'use strict';
var directives = ('directives', []);
([
'$compileProvider',
function($compileProvider) {
   = $;
      }
]);
 = function(directiveName, options) {
var attrs = [];
var fun = null;
if((options)) {
  attrs = (0,  - 1)
  fun = options[ - 1]
} else {
  fun = options;
}
(directiveName, fun);
if ( > 0)
  fun.$inject = attrs;
}
return directives;
});

define(['directives/directives'],
  function(directives) {
  'use strict';
("oprationtable", function() {
    return {
        restrict: 'AE',
        templateUrl: "tpls/",
        transclude: true,
        scope: {
            tabdata: '=',
        },
        link: function(scope, elem, attrs) {
            //()
            // = 
            //()
        },
        controller: function($scope, $element, $attrs) {
        },
     }
 });
});

Okay, the remaining services and filters can be written like this. This is a relatively complete project construction with requirejs and AngularJS. I hope it will be helpful to everyone!

For more information about the use of requirejs AngularJS, please follow my other related articles!