我正在尝试通过范围变量传递模板的URL.范围不会更改,因此模板不需要基于它进行更新,但目前范围变量始终未定义.
<div cell-item template="{{col.CellTemplate}}"></div>
Run Code Online (Sandbox Code Playgroud)
理想情况下,指令将是:
.directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
return {
scope: {
template: '@template'
},
templateUrl: template // or {{template}} - either way
};
}])
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我已经尝试了很多不同的排列来完成相同的概念,这似乎是最接近的,但它仍然不起作用.
.directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
return {
scope: {
template: '@template'
},
link: function (scope, element, attrs) {
var templateUrl = $parse(attrs.template)(scope);
$http.get(templateUrl, { cache: $templateCache }).success(function (tplContent) {
element.replaceWith($compile(tplContent)(scope));
});
}
};
}])
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用ng-include,但在编译之前也没有评估范围变量.CellTemplate值来自数据库调用,因此在评估之前完全未知.任何有关此工作的建议将不胜感激!
编辑:我使用角度1.0.8,我无法升级到更新的版本.
tas*_*ATT 14
你离我不远.
您不需要为指令使用隔离范围.您可以像这样传递templateUrl:
<div cell-item template="col.CellTemplate"></div>
Run Code Online (Sandbox Code Playgroud)
然后添加一个监视以检测模板值何时更改:
.directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
return {
restrict: 'A',
link: function(scope , element, attrs) {
scope.$watch(attrs.template, function (value) {
if (value) {
loadTemplate(value);
}
});
function loadTemplate(template) {
$http.get(template, { cache: $templateCache })
.success(function(templateContent) {
element.replaceWith($compile(templateContent)(scope));
});
}
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
这是一个有效的Plunker:http://plnkr.co/edit/n20Sxq?p = preview
如果您不想自己处理链接逻辑,或者您想要隔离范围,我认为这更简单:
.directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
return {
scope: {
template: '@template'
},
template: "<div ng-include='template'></div>"
};
}])
Run Code Online (Sandbox Code Playgroud)
要么:
template:"<ng-include src='template'></ng-include>"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10949 次 |
最近记录: |