これは、以前の回答のいくつかの問題に対処するフォローアップの回答です。特に、テンプレートを一度コンパイルするだけです(これはページ上にたくさんある場合は重要です。リンクされた後のテンプレートの変更を監視します)、元の要素からクラステンプレートを使用する際には、現在の角度でサポートされている方法とは異なり、スコープ情報を使用して読み込むテンプレートを決定することができます。
.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で再生しようとしますが、私よできないローカル変数の値を取得する方法を示します。私の場合に 'データ 'を得る方法は?私はattrs.dataを試していますが、 'undefined'を返します。 – Agzam
詳細情報があります。テンプレートが$ダイジェストサイクルの一部として動的に変更される可能性があるので、実際に属性の補間を使用するかどうかはわかりません。しかし、本当にしたい場合は、属性を観察する必要があります。 –
私の問題も解決しました。ありがとう! – OpherV