2016-07-14 20 views
1

我正在嘗試創建一個自定義角度組件,該組件可以根據templateUrl函數動態加載模板。我目前得到一個templateUrl沒有使用明確的註解,並且不能在嚴格模式下調用錯誤。通常我知道當注入的服務沒有得到正確的註釋時(https://docs.angularjs.org/error/ $ injector/strictdi),這個錯誤會出現。但是,我錯過了這適用於templateUrltemplateUrl函數沒有使用顯式註釋,並且不能在嚴格模式下調用

我正在使用Angular 1.5。

確切的錯誤信息是 - angular.js:13550 Error: [$injector:strictdi] templateUrl is not using explicit annotation and cannot be invoked in strict mode

組件代碼片段:

angular.module('hive.triGrid') 
.controller('TriGridCellController', ['$element', '$attrs', function  ($element, $attrs) { 
    var $ctrl = this; 
}]) 
.component('triGridCell', { 
controller: 'TriGridCellController', 
templateUrl: function($element, $attrs) 
{ 
    var type = $attrs.cellType; 
    if(type.toUpperCase() == "ICON") 
    { 
     return "components/grid/cellTemplates/iconCell.tpl.html"; 
    } 
    else if(type.toUpperCase() == "CUSTOM") 
    { 
     return $attrs.cellTemplateUrl; 
    } 
    else 
    { 
     return "components/grid/cellTemplates/textCell.tpl.html"; 
    } 
}, 
//template:"<ng-include src='$ctrl.getTemplateUrl(z)'/>", 
bindings: { 
    cellData:'<', 
    cellType: '<', //See triGridRow and triGrid for config JSON format. 
    } 
}); 

編輯: 代碼應用答案後:

templateUrl: ['$element', '$attrs', function($element, $attrs) 
{ 
    var type = $attrs.cellType; 
    if(type.toUpperCase() == "ICON") 
    { 
     return "components/grid/cellTemplates/iconCell.tpl.html"; 
    } 
    else if(type.toUpperCase() == "CUSTOM") 
    { 
     return $attrs.cellTemplateUrl; 
    } 
    else 
    { 
     return "components/grid/cellTemplates/textCell.tpl.html"; 
    } 
}], 

回答

3

至於說in this answer$element$attrs是注入templateUrl函數不只是作爲參數傳遞。這是element參數名稱(在linkcompile函數中)和$element角度文檔強調的啓用DI的函數中的局部依賴性之間的區別。

templateUrl功能是invoked by injector在組件中,所以任何其他服務也可以在那裏注入,它應該被正確註釋。

+0

出於某種原因,我不認爲將其應用於組件設置功能。這對我有效。 – Joseph

+0

這是指令工廠函數的替代品,所以服務可以在需要它們的組件中的每個地方注入。 – estus

+0

我仍然面臨的一個問題是$ attrs.cellType從我的模板返回原始文本,而不是應該傳入的實際控制器值。我試圖根據配置來解析模板,而不是預定義的文本。在這種情況下,我是否需要開始涉足編譯和鏈接以及使用raw指令? – Joseph

相關問題