AngularJS指令,它将自己的标记名设置为定义的字符串
我希望有一个像AngularJS指令,它将自己的标记名设置为定义的字符串,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我希望有一个像这样的标记,可以将级别作为属性传递(嵌套模板传递深度) 这可能看起来像: .directive('hx', function() { return { restrict: 'E', transclude: true, replace: true, link: function(scope, element, attrs) { this.template = '<h' + attrs.level + ' ng-transclude>&
这样的标记,可以将级别作为属性传递(嵌套模板传递深度)
这可能看起来像:
.directive('hx', function() {
return {
restrict: 'E', transclude: true, replace: true,
link: function(scope, element, attrs) {
this.template = '<h' + attrs.level + ' ng-transclude></h' + scope.level + '>'
}
}
})
.directive('hx',function(){
返回{
限制:“E”,转移:真,替换:真,
链接:函数(范围、元素、属性){
this.template=“”
}
}
})
这种方法不能像您在中看到的那样工作。您可以在指令上设置模板。每次运行链接函数时,您都在更改模板。代码中的第一个
元素没有模板,因此不会显示任何内容。第二个将使用第一个(h1)中的模板,第三个将使用第二个(h1)中的模板
相反,您希望对指令使用transclude
功能:
link: function(scope, element, attrs, ctrl, transclude) {
transclude(scope, function (clone) {
const header = angular.element('<h' + attrs.level + '></h' + attrs.level + '>');
header.append(clone);
element.append(header);
// element.replaceWith(header); // variant replace=true
});
}
链接:函数(作用域、元素、属性、ctrl、transclude){
转移(范围、功能(克隆){
常数头=角度元素(“”);
追加(克隆);
元素。追加(标题);
//element.replaceWith(header);//variant replace=true
});
}
这使您可以访问clone
中的转载内容。然后,我们创建具有适当级别的新标题元素,将内容(在clone
中)附加到该元素,然后将该标题元素附加到hx
中
请更具体地说明您遇到的问题。几乎完美!问题是,在您的解决方案中,replace:true不再起作用。我在上面的一篇评论中找到并添加了这个变体。