首頁  >  文章  >  web前端  >  詳解AngularJS中module模組的導入導出_AngularJS

詳解AngularJS中module模組的導入導出_AngularJS

WBOY
WBOY原創
2016-05-16 15:26:201369瀏覽

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
.....helloworld.direcitve.js
.....index.js
.....math.js

app.js

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模組的導入導出,希望大家會喜歡。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn