2013-11-27 179 views
0

我正在製作一個角度應用程序,需要具有可在多個頁面之間重複使用的模塊。設置Angular指令

我做了成功創建一個菜單列表,但目前它已被註冊爲NG-應用它會坐在裏面,像這樣的部分指令:

angular.module('home', []) 
    .directive('Picks', function(){ 
    return { 
     restrict: 'E', 
     scope: false, 
     templateUrl: 'HTML/templateURL.html' 
    }; 
}); 

是的Angular的想法是,我的整個網站建立在一個頁面/ ng-app包裝上?或者,他們可以使這個Picks指令工作,而不需要爲每個將放在其中的ng-app定義它的方式嗎?

希望一切都有道理!

+0

您需要在您定義的每個'ng-app'上註冊您的指令,但通常這隻會是一個頁面上的一個應用程序。當然,沒有理由不能在一個頁面上擁有多個獨立的應用程序。 –

回答

0

在開發模式中,更喜歡使用單獨的js文件作爲指令。如果指令不依賴於家庭應用程序,那麼它也可以在其他應用程序中重新注入。

//file component.js with directive usually alongside their Controllers 
var someModule = angular.module('business', []); 

someModule.directive('Picks', function(){ 
    return { 
     restrict: 'E', 
     scope: false, 
     templateUrl: 'HTML/templateURL.html' 
    }; 
}); 

/*file homepage.js inject the component module as a dependency*/ 
angular.module('home',['business']); 

/*file main.js another app*/ 
angular.module('myApp', ['business']); 


<!-- index.html --> 
<html ng-app="home"> 
... 
<script src="component.js"></script> 
<script src="homepage.js"></script> 
</html> 
<!-- eventually concat and minified for pre production, so it doesn t matter 
how you organized it 
--> 

在實踐中,一些指令使用一些服務/工廠很多。所以他們最終在同一個模塊中。這意味着按功能而不是按類型對模塊進行分組。 這是一個選擇的問題。

+0

感謝Mehery,這很有道理。在我未受教育的條件下:在自己的angular.module中註冊指令,然後在需要時將該模塊作爲依賴項注入其他模塊。 –