当我使用$ 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