1、文件目录结构
2 首先,我们需要main.js文件,RequireJS将会加载这份文件,然后这份文件将会触发加工其他所有依赖的东西。
main.js
* 定义RequireJS配置
*/
require.config({
paths: {
'angular': '../lib/angular/angular',
'angular-route': '../lib/angular-route/angular-route',
'domReady': '../lib/requirejs-domready/domReady'
},
shim: {
'angular': {
exports: 'angular'
},
'angular-route': {
deps: ['angular']
}
},
deps: [
// kick start application... see bootstrap.js
'./bootstrap'
]
});
require( [ 'app', ],
function(app) {
'use strict';
return app.config( [ '$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl : 'partials/partial1.html',
controller : 'MyCtrl1'
});
.when('/view2', {
templateUrl : 'partials/partial2.html',
controller : 'MyCtrl2'
});
.otherwise( {
redirectTo : '/view1'
});
} ]);
}
);
3、然后定义一个app.js文件。这个文件定义了AngularJS应用,并且告诉它去依赖我们所定义的所有控制器、服务、过滤器及指令。
define([
'angular',
'angular-route',
'./controllers/index',
// './directives/index',
// './filters/index',
// './services/index'
], function (angular) {
'use strict';
return angular.module('app', [
'feng.controllers',
// 'directives',
// 'filters',
// 'services',
'ngRoute'
]);
});
4、 我们还有一份bootstrap.js文件,它将会等待DOM结构准备好(使用RequireJS的插件domReady),然后告诉AngularJS一切都已就绪,可以开始运行了。
bootstrap.js
//当DOM结构加载完成后,bootstrap.js文件将会命令AngularJS启动起来并继续执行
define(['angular', 'domReady', 'app'], function(angular, domReady) {
require(['domReady!'], function (document) {
angular.bootstrap(document, ['app']);
});
});
5、index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularJS与RequireJS集成App</title>
</head>
<body>
<ul class="menu">
<li><a href="#/view1">view1</a></li>
<li><a href="#/view2">view2</a></li>
</ul>
<div ng-view></div>
<script src="lib/requirejs/require.js" data-main="js/main.js"></script>
</body>
</html>
6、 下面来看看js/controllers/controllers.js文件里面的内容,它看起来几乎和js/directives/directives.js、js/filters/filters.js及js/services/services一模一样。
define(['angular'], function (angular) {
'use strict';
return angular.module('feng.controllers', []);
});
这里的feng.controllers为设定的所有的controller的模块名。将在app.js中注入
7、 我们组织RequireJS依赖关系的方式会保证在Angular所依赖的内容加载并准备好之后,所有的东西才会运行。
js/controllers/、js/directives/、js/filters/及js/services/里面都会定义一个AngularJS模块,并且对于每一个单独的控制器、指令、过滤器及服务,在声明的时候都会添加对应的模块依赖。
js/controllers/index.js
define([
'./my-ctrl-1',
'./my-ctrl-2'
], function () {});
my-ctrl-1.js
define(['controllers/controllers'], function (controllers) {
'use strict';
controllers.controller('MyCtrl1', [function ($scope) {}]);
});
my-ctrl-1.js
define(['controllers/controllers'], function (controllers) {
'use strict';
controllers.controller('MyCtrl2', [function ($scope) {}]);
});
8、partials/partial1.html
<div>this is view1</div>
<div>this is view2</div>
partials/partial1.html
9、最后你就可以在每个相应的controller中和html中编写逻辑和页面了。