2016-05-14 83 views
13

我一直在試圖用新的角度1.5 component語法項目,但我無法弄清楚如何注入依賴到的組件定義。角1.5組件依賴注入

這是我在重構現有指令到組件的嘗試:

angular 
    .module('app.myModule') 
    .component('row', { 
     bindings: { 
     details: '@', 
     zip: '@' 
     }, 
     controller: 'RowController', 
     templateUrl: basePath + 'modules/row.html' // basePath needs to be injected 
    }) 

由於種種原因,我們注入恆basePath到我們所有的指令作爲templateUrl的一部分。

如何做到這一點的部件上,因爲組件定義不是一個功能?

回答

14

您可以使用功能templateUrl構造URL。然而,不同於一個用於指令,組分templateUrl功能是注射(參考docs),這意味着你可以注入恆定(或任何其它可注射的服務)到它。正是你所需要的:

.component('row', { 
    bindings: { 
    details: '@', 
    zip: '@' 
    }, 
    controller: 'RowController', 
    templateUrl: function(basePath, $rootScope) { // $rootScope is an example here 
    return basePath + 'modules/row.html' 
    } 
}) 

微小安全數組符號也被支持:

templateUrl: ['basePath', '$rootScope', function(basePath, $rootScope) { 
    return basePath + 'modules/row.html' 
}] 

演示:http://plnkr.co/edit/jAIqkzZGnaEVPaUjyBrJ?p=preview

+0

完美!我沒有想到將templateUrl變成一個函數。 – epb