gpt4 book ai didi

angularjs - 当我在 svg 中使用 AngularJS 指令时,结果不显示

转载 作者:行者123 更新时间:2023-12-04 23:22:44 24 4
gpt4 key购买 nike

我正在尝试创建我将在 svg 元素中使用的 AngularJS 指令。
该指令不创建 svg 元素,而是使用现有元素。
我可以在开发工具中看到正确的 svg 标记,但浏览器没有显示它。

Please see live example .

这是指令:

angular.module('ui.directives', []).directive('svgText', 
function() {
return {
restrict: 'E',
replace: true,
template: '<text fill="green" x="4" y="20" font-weight="bolder" font-size="2" font-family="Arial">89</text>'
};
}
);

最佳答案

发生这种情况是因为 jQuery(AngularJS 在幕后使用的)不知道如何创建 svg 元素。您可以通过将链接函数添加到克隆已创建元素但在 SVG 命名空间中创建它的指令中来解决此问题。

一个可能更好的方法是将您的模板包装在一个 SVG 元素(定义了命名空间)中,然后在链接函数中拉出子元素并使用它,它已经在正确的命名空间中创建。

module.directive(
'svgText',
function () {
return {
restrict: 'E',
template: '<svg xmlns="http://www.w3.org/2000/svg"><text fill="green" x="4" y="20" font-weight="bolder" font-size="2" font-family="Arial">89</text></svg>',
replace: true,

link: function (scope, elem, attrs) {
// Extract the child element to replace the SVG element.
var child = angular.element(elem[0].firstElementChild);

// Copy attributes into element.
for (attrName in attrs) {
if(typeof attrs[attrName] === "string") {
child.attr(attrName, attrs[attrName]);
}
}
elem.replaceWith(child );
}
};
}
);

我发表了一篇关于 AngularJS + SVG 的文章,其中讨论了许多此类问题。

http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

关于angularjs - 当我在 svg 中使用 AngularJS 指令时,结果不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19777982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com