这是一个后续答案,解决了先前答案的一些问题。值得注意的是,它只会编译一次模板(如果您的页面上有很多模板,这一点很重要,并且它会在模板链接后监视模板的更改。它还将类和样式从原始元素复制到模板(尽管当您使用“replace:true”时,Angular 不会以非常优雅的方式在内部执行。与当前使用模板或 templateUrl 的函数的 Angular 支持方法不同,您可以使用范围信息来确定要加载的模板。
.directive('boom', ['$http', '$templateCache', '$compile', function ($http, $templateCache, $compile) {
//create a cache of compiled templates so we only compile templates a single time.
var cache= {};
return {
restrict: 'E',
scope: {
Template: '&template'
},
link: function (scope, element, attrs) {
//since we are replacing the element, and we may need to do it again, we need
//to keep a reference to the element that is currently in the DOM
var currentElement = element;
var attach = function (template) {
if (cache[template]) {
//use a cloneAttachFn so that the link function will clone the compiled elment instead of reusing it
cache[template](scope, function (e) {
//copy class and style
e.attr('class', element.attr('class'));
e.attr('style', element.attr('style'));
//replace the element currently in the DOM
currentElement.replaceWith(e);
//set e as the element currently in the dom
currentElement = e;
});
}
else {
$http.get('/pathtotemplates/' + template + '.html', {
cache: $templateCache
}).success(function (content) {
cache[template] = $compile(content);
attach(template);
}).error(function (err) {
//this is something specific to my implementation that could be customized
if (template != 'default') {
attach('default');
}
//do some generic hard coded template
});
}
};
scope.$watch("Template()", function (v, o) {
if (v != o) {
attach(v);
}
});
scope.$on('$destroy', function(){
currentElement.remove();
});
}
};
} ])