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模塊的導入導出,希望大家喜歡。
新聞熱點
疑難解答