引言
最近一个项目要使用requirejs实现angularjs的js文件按需加载,在网上我也找了很多资料但是都不是很全,要么就不是很详细,所以我自己总结了一下,有需要的朋友可以看一下。废话不多说,直接上代码。
一、简单事例的项目目录如下:
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大概如下
<!doctype html>
<!-- <html xmlns:ng="//angularjs.org" id="ng-app"
ng-app="webapp"> -->
<htmls>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge, chrome=1">
</head>
<body>
<!--其他html内容-->
<script data-main="js/main" src="../lib/require/require.min.js"></script>
</script>
</body>
</html>在首页index.html只需要引入requirejs库文件,并且指明入口函数main.js,采用手动启动angularjs应用,所以这里不用为首页添加ng-app='webapp'。
三、配置mian.js
定义requirejs配置
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结构加载完成后,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;
});
主要用来加载各个控制器(所有的控制器都将在这个文件中被加载),除此之外再不用做其他,因为我们可以有很多个控制器文件,按照具体需要进行添加。
contreller1.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也类似。
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结合使用项目搭建 希望对大家有帮助!
发表评论