2016-08-03 52 views
2

我正在開發一個模塊化角度應用程序,我在angular-module-1模塊中定義了我的文件夾路徑(常量:BASE_PATH:「path/to/folder」)。我想在我的應用程序的另一個模塊(angular-module-2)中的角度組件中重新使用此常量。我想在我的項目中多次使用這個常量。角度組件相對模板UIr

module.component("relationshipSearch", { 
templateUrl: BASE_PATH +'/link/to/other/folder', 

女巫來定義這個常量作爲一個全局變量中的所有解決方案項目 可見的最好辦法這裏是我的項目結構:

project 
|-- angular-module-1 
| |-- angular-module-1.js 
| |-- angular-module-1.html 
|-- angular-module-2 
| |-- angular-module-2.js 
| |-- angular-module-2.html 

回答

3

我想說的是創建,命名爲angular-common一個共同的模塊,你可以把common東西一樣常見servicefactorydirectiveconstants

然後添加常數內angular-common(這將是完全獨立的和可插拔)模塊。像下面

//assuming `angular-common` is already defined 
angular.module('angular-common').constant('commmonSetting', { 
    'BASE_PATH': '/link/to/other/folder' 
}) 

接下來,在app注入這一共同的模塊(這是主要的模塊,將在ng-app/bootstrap使用)像下面

angular.module('app', ['angular-common', 'ngRoute', ...other dependencies..]) 

當你想使用BASE_PATH剛剛注入commmonSetting無論你在哪裏,都需要依賴controller/component

app.component('myComponent', { 
    templateUrl: function(commmonSetting){ 
    return commmonSetting.BASE_PATH +'/link/to/other/folder'; 
    }, 
    .... 
}) 
+0

謝謝,我需要:) – Saad

-1

也許不同的方法可能有幫助。而不是設置路徑,爲什麼不只是查看同一目錄中的文件。

你可以使用require(),例如:

template: require('./template-in-same-dir.html') 

templatetemplateUrl

+0

我問的角度應用程序的不同模塊之間共享/重新使用常數的最佳方式。 – Saad

+0

然而標題問一個模板的網址 – zilj

+0

我仍然認爲我對你的具體問題的解決方案值得考慮。通過創建多個模塊,您爲了一個字符串將它們連接在一起。似乎過度。但是,當然有很多方法來烘烤蛋糕,它只取決於哪一個是我們最喜歡的風味! :) – zilj

2

對不起,張貼在一個古老的線程與一個公認的答案,但我想說,接受的答案是不是縮小安全。小寫安全的方式寫這是:

app.component('myComponent', { 
    templateUrl: function($injector){ 
    var commmonSetting = $injector.get('namespace.CommmonSetting'); 
    return commmonSetting.BASE_PATH +'/link/to/other/folder'; 
    }, 
    .... 
});