这是一个后续的答案,解决了以前的答案的几个问题。值得注意的是,它只会编译一次模板(如果页面上有很多这样的内容,这很重要,它会在模板链接后监视模板的更改,还会将类和样式从原始元素复制到模板(尽管在使用“replace:true”的时候,角度并没有采用非常优雅的方式)。与使用template或templateUrl函数的当前角度支持方法不同,您可以使用示波器信息来确定要加载的模板
.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();
});
}
};
} ])
是啊,我试图用ngInclude玩,但我不能f ind如何获得局部变量的值。如何在我的情况下获得'数据'?我正在尝试attrs.data,但它返回'undefined' – Agzam
提供了更多信息。我不确定是否真的想要使用插值属性,因为这意味着模板可以作为$ digest循环的一部分动态更改。但如果你真的想这样做,你将不得不$观察属性。 –
解决了我的问题。谢谢! – OpherV