2016-08-08 129 views
2

我嘗試使用指令參數化頁面的模板。 我有一個'類型'值的對象數組。我想在類型不同時使用不同的模板。AngularJS指令templateUrl函數使用雙向數據綁定

這裏是我的嘗試:

directive.js

angular.module('core') 
    .directive('mySolutionDisplay', function() { 
    return { 
     restrict: 'E', 
     scope: { 
     solution: '=' 
     }, 
     templateUrl: function (elem, attr) { 
     return 'path/to/template/solution-'+attr.type+'.template.html'; 
     } 
    }; 
    }); 

view.html

<div class="row"> 
    <my-solution-display type="vm.solution[0].type" solution="vm.solution"></my-solution-display> 
</div> 

我得到以下錯誤: angular.js:11706 Error: [$compile:tpload] Failed to load template: path/to/template/solution-vm.solution[0].type.template.html

我試着用type="{{vm.solution[0].type}}"替換type="vm.solution[0].type",但它只是在錯誤信息中加上大括號。

+0

+0

你有沒有試過這樣的,我覺得在TYPE =「」它不能解決變量名和你可以嘗試在那裏添加大括號 –

回答

0

屬性(attrs)無權訪問範圍變量。他們插入後得到dom值。

因此,使用

<my-solution-display type="{{vm.solution[0].type}}" solution="vm.solution"> </my-solution-display>

注意如何type="vm.solution[0].type"變更爲type="{{vm.solution[0].type}}"

+0

我已經試過這個,但它只是在錯誤描述中添加大括號。 'angular.js:11706錯誤:[$ compile:tpload]無法加載模板:path/to/template/solution - {{vm.solution [0] .type}}。template.html' – JulienM

+1

是的,忽略我的回答。看起來這是不可能的。查看錯誤:https://github.com/angular/angular.js/issues/13526。 看看:http://stackoverflow.com/questions/21835471/angular-js-directive-dynamic-templateurl解決這個問題的另一種方法。 – Chanthu