AngularJS 将自己的标签名称设置为已定义字符串的指令
AngularJS directive that sets its own tag name to a defined string
我想要一个像 <h1>
这样的标签,我可以将级别作为属性传递(对于嵌套模板传递深度)。
这可能看起来像:
.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 + '>'
}
}
})
中所见,此方法无法按预期工作
您可以在指令上设置模板。每次 link 函数运行时,您都在更改模板。您代码中的第一个 <hx>
元素没有模板,因此不会出现任何内容。第二个将使用第一个 (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
});
}
这使您可以访问 clone
中嵌入的内容。然后,我们创建具有适当级别的新 header 元素,将内容(在 clone
中)附加到该元素,然后将该 header 元素附加到 hx
。
我想要一个像 <h1>
这样的标签,我可以将级别作为属性传递(对于嵌套模板传递深度)。
这可能看起来像:
.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 + '>'
}
}
})
中所见,此方法无法按预期工作
您可以在指令上设置模板。每次 link 函数运行时,您都在更改模板。您代码中的第一个 <hx>
元素没有模板,因此不会出现任何内容。第二个将使用第一个 (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
});
}
这使您可以访问 clone
中嵌入的内容。然后,我们创建具有适当级别的新 header 元素,将内容(在 clone
中)附加到该元素,然后将该 header 元素附加到 hx
。