當我使用$ compile爲我的指令創建一個動態模板時,我遇到了作用域丟失的問題。請參閱下面的代碼(爲了清晰起見而修剪):
(function() {
'use strict';
angular.module('cdt.dm.directives').directive('serviceSources', ['$http', '$templateCache', '$compile', '$parse',
function ($http, $templateCache, $compile, $parse) {
return {
restrict: 'E',
replace: true,
scope: {
type: '=',
sources: '='
},
link: function (scope, element, attr) {
var template = 'Template_' + scope.type + '.html';
$http.get(template, { cache: $templateCache }).success(function (tplContent) {
element.replaceWith($compile(tplContent)(scope));
});
$compile(element.contents())(scope);
}
}
}
])
})();
工作和html模板被加載。
HTML模板看起來像:
<table>
<thead>
<tr>
<th>File</th>
</tr>
</thead>
<tbody data-ng-reapeat="src in sources">
<tr>
<td>{{src.fileName}}</td>
</tr>
</tbody>
源是具有兩個元件的陣列。在指令的範圍內,它是絕對正確的,但在模板中,ng-repeat不起作用(我猜是因爲在這個階段源未定義)。
有人知道我在做什麼錯嗎?
我不知道你是否可以使用'templateUrl'來代替? –
不,模板需要是動態的,基於傳遞給作用域'type'變量的值。所以我不能使用templateUrl。 – Sam
我已根據您的建議編輯了原始代碼,謝謝。 – Sam