在 angular documentation for the compile service (starting at line 412)有传递到指令链接函数的 transclude 函数的描述。
相关部分内容如下:
function([scope], cloneLinkingFn, futureParentElement)
其中(第 212 行):
futureParentElement
: defines the parent to which thecloneLinkingFn
will add the cloned elements.
default:
$element.parent()
resp.$element
fortransclude:'element'
resp.transclude:true
.only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) and when the
cloneLinkinFn
is passed, as those elements need to created and cloned in a special way when they are defined outside their usual containers (e.g. like<svg>
).See also the
directive.templateNamespace
property.
我没看清
futureParentElement
的要点然而。它说defines the parent to which the cloneLinkingFn will add the cloned elements.
但是您在
cloneLinkingFn
中这样做了本身是这样的:transclude(scope, function (clone) {
some_element.append(clone);
});
并且您不能在不首先定义克隆函数的情况下使用 transclude 函数。
futureParentElement
的正确用法/用法是什么? ?
最佳答案
可以通过查看 git blame of compile.js
找到答案。 : 添加 futureParentElement
的提交是 https://github.com/angular/angular.js/commit/ffbd276d6def6ff35bfdb30553346e985f4a0de6
在提交中有一个测试指令 svgCustomTranscludeContainer
directive('svgCustomTranscludeContainer', function() {
return {
template: '<svg width="400" height="400"></svg>',
transclude: true,
link: function(scope, element, attr, ctrls, $transclude) {
var futureParent = element.children().eq(0);
$transclude(function(clone) {
futureParent.append(clone);
}, futureParent);
}
};
});
通过测试如何编译html
<svg-custom-transclude-container><circle cx="2" cy="2" r="1"></circle>
行为:it('should handle directives with templates that manually add the transclude further down', inject(function() {
element = jqLite('<div><svg-custom-transclude-container>' +
'<circle cx="2" cy="2" r="1"></circle></svg-custom-transclude-container>' +
'</div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var circle = element.find('circle');
assertIsValidSvgCircle(circle[0]);
}));
因此,如果您使用指令创建 SVG 图像,该指令的模板将嵌入的 SVG 内容包装在
<svg> ... </svg>
中。标签,那么该 SVG 图像将无效(根据某种定义),如果您没有传递正确的 futureParentElement
至 $transclude
.试图了解无效实际上意味着什么,除了源代码中的测试之外,我根据单元测试中的指令创建了 2 个指令,并使用它们尝试创建带有部分圆的 SVG 图像。一个使用
futureParentElement
:<div><svg-custom-transclude-container-with-future><circle cx="1" cy="2" r="20"></circle></svg-custom-transclude-container></div>
和一个相同但不相同的:
<div><svg-custom-transclude-container-without-future><circle cx="2" cy="2" r="20"></circle></svg-custom-transclude-container></div>
如在 http://plnkr.co/edit/meRZylSgNWXhBVqP1Pa7?p=preview 处可见,与
futureParentElement
的那个显示部分圆圈,没有的没有。 DOM 的结构看起来是相同的。然而,Chrome 似乎报告了第二个 circle
element 不是一个 SVG 节点,而是一个普通的 HTML 节点。所以无论如何
futureParentElement
实际上在幕后,它似乎确保嵌入的 SVG 内容最终被浏览器作为 SVG 处理。
关于angularjs - 指令链接函数的transclude函数中, "futureParentElement"是怎么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30735054/