RequireJS与AngularJS结合使用示例解析
引言 近期,一个项目需要将 AngularJS 与 RequireJS 配合使用,以实现 JavaScript 文件的按需加载。此类需求在实际开发中较为常见,但网络上可参考的资料大多零散或不够详尽。本文整合了一份完整的实践记录,从项目结构到具体配置,逐步说明实现过程。以下直接展示代码与实现思路。 一
引言
近期,一个项目需要将 AngularJS 与 RequireJS 配合使用,以实现 JavaScript 文件的按需加载。此类需求在实际开发中较为常见,但网络上可参考的资料大多零散或不够详尽。本文整合了一份完整的实践记录,从项目结构到具体配置,逐步说明实现过程。以下直接展示代码与实现思路。

一、示例项目的目录结构
index.html
js 文件夹
--controller文件夹 --- controllers.js --- controller1.js ---controller2.js --directives文件夹 ---directives.js ---directive1.js --app.js --router.js --loader.js --main.js --angular-bootstrap.js
二、首页
首页 index.html 的编写方式如下。注意,此处没有在 html 标签上添加 ng-app,因为需要手动启动 AngularJS 应用。
首页仅引入 RequireJS 库文件,并指定入口文件 main.js。由于需要手动启动 AngularJS,因此无需在首页上添加 ng-app='webApp'。
三、配置 main.js
定义 RequireJS 的配置,包括路径和 shim 依赖。
require.config({
urlArgs: "==version==",
waitSeconds: 0,
paths: {
'jquery': '../../plugins/jQuery/jQuery-2.1.4.min',
'bootstrap': '../../lib/bootstrap/dist/js/bootstrap.min',
'angular': '../../lib/angular/angular.min',
'angular-route': '../../lib/angular-route/angular-route.min',
'angular-animate': '../../lib/angular-animate/angular-animate.min',
'angular-resource': '../../lib/angular-resource/angular-resource.min',
'angular-growl': '../../lib/angular-growl-v2/build/angular-growl.min',
'domReady': '../../lib/require/domReady',
'jquery-ui': '../../lib/jquery-ui/jquery-ui.min',
},
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',
// 这是导入一个方法
'loader',
//注意:这不是Twitter Bootstrap,而是AngularJS bootstrap
'angular-bootstrap',
//所创建的所有控制器、服务、指令及过滤器文件都必须写到这里,这块内容必须手动维护
'controllers/controllers',
'directives/directives',
],
function(app, config, loader) {
'use strict';
app.config([
'$routeProvider',
'$locationProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
"$httpProvider",
'growlProvider',
function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $httpProvider, growlProvider) {
app.registerController = $controllerProvider.register;
app.registerDirective = $compileProvider.directive;
app.registerFilter = $filterProvider.register;
app.registerFactory = $provide.factory;
app.registerService = $provide.service;
console.log("config.routes"+config.routes);
if(config.routes != undefined) {
angular.forEach(config.routes, function(route, path) {
$routeProvider.when(path, {
templateUrl: route.templateUrl,
controller: route.controller,
resolve: loader(route.dependencies)
});
});
}
if(config.defaultRoutePath != undefined) {
$routeProvider.otherwise({
redirectTo: config.defaultRoutePath
});
}
growlProvider.globalTimeToLive({
success: 3000,
error: 5000,
warning: 5000,
info: 5000
});
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
return app;
}
);
main.js 的核心功能是由 RequireJS 异步加载所有文件;后续的 function 中处理各项依赖方法。
四、手动启动 AngularJS 应用
angular-bootstrap.js 文件负责在 DOM 加载完成后手动启动 AngularJS:
//当DOM结构加载完成后,bootstrap.js文件将会命令AngularJS启 动起来并继续执行
define(['angular', 'domReady', 'app'], function(angular, domReady) {
require(['domReady!'], function(document) {
angular.bootstrap(document, ['app']);
});
});
该文件依赖 app.js 和 router.js,下面分别说明它们的作用。
五、angular.module
通常编写 AngularJS 应用的形式如下:
var app = angular.module("xxx",["xxx"]);
app.controller("foo",function($scope){});
app.directive(...)
因此 app.js 的组织方式为:
define([
'angular',
'angular-route',
'angular-resource',
'angular-animate',
'angular-growl',
'angular-animate',
。。。
], function(angular) {
'use strict';
return angular.module('app', [
'controllers',
'directives',
'angular-growl',
'ngAnimate',
'ngRoute',
。。。
]);
});
六、网站路由设置
使用 ng-router 定义路由。router.js 的写法如下,关于 ng-router 的详细配置可自行查阅,此处仅展示按需加载的关键点。
router.js
define([], function() {
return {
defaultRoutePath: '/index',
routes: {
'/index': {
templateUrl: 'tpls/index.html',
controller: 'indexCtr',
dependencies: ['js/controllers/index.js', 'js/directives/derective1.js']
//这就是按需导入js文件
},
}
};
});
还需要一个 loader 文件,其中定义了按需加载的方法。
loader.js
define([], function() {
return function(dependencies) {
// 返回路由的 resolve 定义,
var definition = {
// resolver 是一个函数, 返回一个 promise 对象;
resolver: ['$q', '$rootScope', function($q, $rootScope) {
// 创建一个延迟执行的 promise 对象
var defered = $q.defer();
// 使用 requirejs 的 require 方法加载的脚本
require(dependencies, function() {
$rootScope.$apply(function() {
// 加载完脚本之后, 完成 promise 对象;
defered.resolve();
});
});
//返回延迟执行的 promise 对象, route 会等待 promise 对象完成
return defered.promise;
}]
};
return definition;
}
});
七、控制器
首先,controllers.js 需要具备以下结构:
define(['angular'], function(angular) {
'use strict';
var controllers = angular.module('controllers', []);
controllers.config([ '$controllerProvider', function($controllerProvider) {
controllers.registerController = $controllerProvider.register;
}
]);
controllers.initController = function(controllerName, options) {
var attrs = [];
var fun = null;
if(jQuery.isArray(options)) {
attrs = options.slice(0, options.length - 1)
fun = options[options.length - 1]
} else {
fun = options;
}
controllers.registerController(controllerName, fun);
if (attrs.length > 0)
fun.$inject = attrs;
}
return controllers;
});
主要职责是加载各个控制器,所有控制器均通过该文件注册,后续只需按需添加具体的控制器文件。
controller1.js 的具体写法:
define(['controllers/controllers'], function(controllers) {
'use strict';
controllers.initController('user_centerCtrl', ['$scope', '$location', '$routeParams', '$timeout', '$http',
function($scope, $location, $routeParams, $timeout, $http) {
}
]);
});
八、指令
directives.js 的结构与 controllers.js 类似:
define(['angular'], function(angular) {
'use strict';
var directives = angular.module('directives', []);
directives.config([
'$compileProvider',
function($compileProvider) {
directives.registerDirective = $compileProvider.directive;
}
]);
directives.initDirective = function(directiveName, options) {
var attrs = [];
var fun = null;
if(jQuery.isArray(options)) {
attrs = options.slice(0, options.length - 1)
fun = options[options.length - 1]
} else {
fun = options;
}
directives.registerDirective(directiveName, fun);
if (attrs.length > 0)
fun.$inject = attrs;
}
return directives;
});
directive1.js 示例:
define(['directives/directives'],
function(directives) {
'use strict';
directives.initDirective("oprationtable", function() {
return {
restrict: 'AE',
templateUrl: "tpls/operationTable.html",
transclude: true,
scope: {
tabdata: '=',
},
link: function(scope, elem, attrs) {
//console.log(attrs.tabdata)
//scope.tabdata = attrs.tabdata
//console.log(scope.tabdata)
},
controller: function($scope, $element, $attrs) {
},
}
});
});
其余的服务、过滤器等均可按相同方式组织。以上即为一个较为完整的 RequireJS 与 AngularJS 结合实现按需加载的项目搭建方案,供参考。
