我正在编写一个指令,它根据提供的属性采用模板。
JS
var app = angular.module('app', []);
app.directive('sample', function($compile){
var a = '<div>template 1</div>';
var b = '<div>template 2</div>';
return {
replace: true,
restrict: 'E',
scope: {
type: '@'
},
link: function($scope, $element){
var get_template = function(){
if($scope.type == 'others'){
return b;
} else {
return a;
}
};
$($element).html(get_template()).show();
$compile($($element).contents())($scope);
}
}
});
HTML
<sample></sample>
<sample type="others"></sample>
这里replace: true
当我们在指令中提供模板属性时,它就可以工作。有什么办法可以摆脱<sample />
标签,只需 <div />
.
还有另一种方法,
app.directive('sample', function($compile, $templateCache){
var a = '<div>template 1</div>';
var b = '<div>template 2</div>';
$templateCache.put('template1.html', a);
$templateCache.put('template2.html', b);
return {
template: '<div ng-include="get_template()" />',
replace: true,
restrict: 'E',
scope: {
type: '@'
},
link: function($scope, $element){
var get_template = function(){
if($scope.type == 'others'){
return 'template2.html';
} else {
return 'template1.html';
}
};
}
}
});
但是上面的做法还是有<div ng-include />
作为 <div>template1</div>
的父级而我只需要 <div>template
.
有什么办法吗?
提前致谢。
最佳答案
您可以在 Angular 中使用restrict,将其限制为“A”并添加“sample”作为属性。
了解有关指令中限制的更多信息:AngularJS Directive Restrict A vs E
关于javascript - Angular Directive - 在嵌入模板时替换标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879870/