您的位置:首页 > Web前端 > AngularJS

AngularJS中module的导入导出

2015-12-10 12:17 661 查看
关于AngularJS中module的导入导出,在Bob告诉我之前还没写过,谢谢Bob在这方面的指导,给到我案例代码。

在AngularJS实际项目中,我们可能需要把针对某个领域的各个方面放在不同的module中,然后把各个module汇总到该领域的一个文件中,再由主module调用。就是这样:



以上,app.mymodule1, app.mymodule2,app.mymodule都是针对某个领域的,比如app.mymodule1中定义directive, app.mymodule2中定义controller, app.mymodule把app.mymodule1和app.mymodule2汇总到一处,然后app这个主module依赖app.mymodule。

文件结构:

mymodule/
.....helloworld.controller.js <在app.mymodule2中>
.....helloworld.direcitve.js <在app.mymodule1中>
.....index.js <在app.mymodule中>
.....math.js <在一个单独的module中>
app.js <在app这个module中>
index.html

helloworld.controller.js:

var angular = require('angular');
module.exports = angular.module('app.mymodule2', []).controller('HWController', ['$scope', function ($scope) {

$scope.message = "This is HWController";

}]).name;


以上,通过module.exports导出module,通过require导入module。

helloworld.direcitve.js:

var angular=require('angular');

module.exports = angular.module('app.mymodule1', []).directive('helloWorld', function () {
return {
restrict: 'EA',
replace: true,
scope: {
message: "@"
},
template: '<div><h1>Message is {{message}}.</h1><ng-transclude></ng-transclude></div>',
transclude: true
}
}).name;


接着,在index.js把pp.mymodule1和app.mymodule2汇总到一处。

var angular = require('angular');
var d = require('./helloworld.directive');
var c = require('./helloworld.controller');

module.exports = angular.module('app.mymodule', [d, c]).name;


在math.js中:

exports = {
add: function (x, y) {
return x + y;
},
mul: function (x, y) {
return x * y;
}
};


最后,在app.js中引用app.mymodule1:

var angular = require('angular');
var mymodule = require('./mymodule');
var math = require('./mymodule/math');

angular.module('app', [mymodule])
.controller('AppController', ['$scope', function ($scope) {
$scope.message = "hello world";
$scope.result = math.add(1, 2);
}]);


以上, require('./mymodule');会自动到mymodule文件中找index.js中的module,这个是惯例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: