使用 $compile 为我的指令创建动态模板时,我遇到范围丢失的问题。请参阅下面的代码(为清楚起见进行了 trim ):
(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>
sources 是一个包含两个元素的数组。在指令的范围内,它绝对是正确的,但在模板中,ng-repeat不起作用(我猜是因为现阶段源未定义)。
有人知道我做错了什么吗?
最佳答案
我认为有一个拼写错误:ng-repeat
而不是data-ng-reapeat
,和ng-repeat
应放在 <tr>
<table>
<thead>
<tr>
<th>File</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="src in sources">
<td>{{src.fileName}}</td>
</tr>
</tbody>
请注意$http.get
是异步的,记得将代码包装在 scope.$apply
内。您应该像这样修改您的代码:
link: function (scope, element, attr) {
var template = 'Template_' + scope.type + '.html';
$http.get(template, { cache: $templateCache }).success(function (tplContent) {
scope.$apply(function(){
element.replaceWith(tplContent);
$compile(element)(scope);
//Or
//element.html(tplContent);
//$compile(element.contents())(scope);
});
});
}
关于javascript - angularjs:使用 $compile 时指令中的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19182823/