詳解AngularJS中module模塊的導入導出
AngularJS是一款來自Google的前端JS框架,它的核心特性有:MVC、雙向數據綁定、指令和語義化標簽、模塊化工具、依賴注入、HTML模板,以及對常用工具的封裝,例如$http、$cookies、$location等。
關于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);
}]);
以上所述是小編給大家分享的AngularJS中module模塊的導入導出,希望大家喜歡。
相關文章
Angular2中如何使用ngx-translate進行國際化
本篇文章主要介紹了Angular2中使用ngx-translate進行國際化,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
利用JavaScript的AngularJS庫制作電子名片的方法
這篇文章主要介紹了利用JavaScript的AngularJS庫制作電子名片的方法,其中需要使用到HTML5的canvas畫布,需要的朋友可以參考下2015-06-06

