AngularJS中module的導入導出


 

關於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,這個是慣例。  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM