发生这种情况是因为 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