2013-10-01 30 views
44

我需要爲AngularJS編寫一個自定義模塊,但是我找不到關於這個主題的任何好文檔。我如何爲AngularJS編寫自定義模塊,以便與其他人分享?如何爲AngularJS編寫自定義模塊?

+1

此博客幫我AngularJs很多的模塊[13個步驟AngularJS模塊化(https://blog.safaribooksonline.com/2014/03/27/13-step-guide-angularjs-modularization/)。 – danijelf

回答

80

在這種情況下是你認爲的文檔不能幫你了,要學會一個很好的辦法就是看看其他已經建立模塊,看看別人怎麼做的,他們是如何設計的架構,以及如何他們將它們整合到他們的應用程
看過其他人做了什麼之後,你至少應該有一個起點。

例如,看看任何angular ui module,你會看到很多自定義模塊。
一些定義just a single directive,而另一些定義more stuff

@nXqd表示,要創建一個模塊的基本方法是:

// 1. define the module and the other module dependencies (if any) 
angular.module('myModuleName', ['dependency1', 'dependency2']) 

// 2. set a constant 
    .constant('MODULE_VERSION', '0.0.3') 

// 3. maybe set some defaults 
    .value('defaults', { 
     foo: 'bar' 
    }) 

// 4. define a module component 
    .factory('factoryName', function() {/* stuff here */}) 

// 5. define another module component 
    .directive('directiveName', function() {/* stuff here */}) 
;// and so on 

定義你的模塊後,它很容易將組件添加到它(而無需將模塊存儲在一個變量):

// add a new component to your module 
angular.module('myModuleName').controller('controllerName', function() { 
    /* more stuff here */ 
}); 

集成部分相當簡單:只需將它作爲依賴項添加到您的應用程序模塊(here's UI ui是如何實現的)。

angular.module('myApp', ['myModuleName']); 
+0

thx這兩個答案。我會接受來自gion_13的,因爲它更詳細。 –

+0

「只有一條指令」鏈接被破壞。 –

+0

@ Mariusz.W謝謝你的擡頭。在我的原始答案中,angular-ui github組織更新/移動了我鏈接的大部分回購券,現在每個鏈接都已被打破。用新的例子更新它們。 –

5

如果你想尋找一個很好的例子,你應該看看寫在angularJS當前模塊。學習閱讀他們的源代碼。順便說一句,這是我用angularJS編寫模塊的結構:

var firstModule = angular.module('firstModule', []) 
firstModule.directive(); 
firstModule.controller(); 

// in your app.js, include the module 

這是最基本的一個。

2
var newMod = angular.module('newMod', []); 

newMod.controller('newCon', ['$scope', function ($scope) { 
    alert("I am in newCon"); 
    $scope.gr = "Hello"; 
}]); 

這裏爲NewMod是不具有依賴性[],並且具有其具有警報告訴你在控制器和帶有值你好變量的控制器的模塊。