AngularJS中module的导入导出

在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,这个是惯例。  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值