我正在尝试通过作用域变量传递模板的url。范围不会更改,因此模板不需要基于模板进行更新,但是当前范围变量始终是未定义的。
<div cell-item template="{{col.CellTemplate}}"></div>
理想情况下,该指令应为:
.directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
return {
scope: {
template: '@template'
},
templateUrl: template // or {{template}} - either way
};
}])
但是,这不起作用。为了实现相同的概念,我尝试了许多不同的排列方式,这似乎是最接近的,但是仍然无法正常工作。
.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));
});
}
};
}])
我也尝试过使用ng-include,但是在编译之前也不会评估作用域变量。 CellTemplate值来自数据库调用,因此在评估之前是完全未知的。任何建议,使这项工作将不胜感激!
编辑:
我正在使用angular 1.0.8,但无法升级到较新的版本。
最佳答案
你一点也不远。
您无需为指令使用隔离范围。您可以像这样传递templateUrl:
<div cell-item template="col.CellTemplate"></div>
然后添加一个监视以检测模板值何时更改:
.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));
});
}
}
}
}]);
这是一个工作的柱塞:http://plnkr.co/edit/n20Sxq?p=preview
关于angularjs - 如何通过属性中的作用域变量传递templateUrl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501584/