2014-11-04 30 views
3

我想知道對多個模塊重用相同指令的最佳方式是什麼。在我看來,我認爲指令就像DOM模塊,所以角度的架構對我的觀點來說有點煩人。爲多個模塊重用指令

我現在做它的方式是:

var mainapp = angular.module('MainApp'); 
mainapp.controller(...); 

var otherapp = angular.module('OtherApp'); 
otherapp.controller(...); 

而在其他文件中,我有我的指導,我想在這兩個控制器使用/模塊

mainapp.directive('autoselect', function(){ ... }); 

但你可以看,我必須指定我必須使用它的應用程序。如果我想在兩者中使用,是否必須複製兩次相同的代碼?

回答

5

您可以維護一個包含常見模塊(服務,指令,值,常量等)並注入到每個模塊中。

angular.module('CommonApp',['OtherCommonModule1','OtherCommonModule2']).directive(..); 

var mainapp = angular.module('MainApp', ['CommonApp']); 
mainapp.controller(...); 

var otherapp = angular.module('OtherApp', ['CommonApp']); 
otherapp.controller(...); 
+0

你打我吧! :) – Digitrance 2014-11-04 03:49:56

3

不,你沒有指定你需要使用一個指令,它的應用程序/模塊

讓我解釋一下:

  1. 在angularJS,一切都是一個模塊。例如,MainApp,OtherApp,甚至是autoselect指令都是一個模塊。
  2. 每個模塊都可以「依賴」一個或多個模塊。

所以,這裏是我會怎麼設計解決方案:

angular.module('com.example.mydirective', []) 
    .directive('autoselect', function() { ... }); 

angular.module('MainApp', ['com.example.mydirective']); 
    .controller(...); 

angular.module('OtherApp', ['com.example.mydirective']); 
    .controller(...); 

有一件事我想補充:在方括號表示依賴具有特殊意義。

angular.module('module-name', []); // this line tells angularJS to create a new module 

angular.module('module-name'); // no brackets -- this asks angularjs to return a pre-existing module 

希望這有助於