当我在SVG中使用AngularJS指令时,结果没有呈现。

4
我正在尝试创建AngularJS指令,将其用于svg元素内部。该指令不会创建svg元素,而是使用现有的元素。我可以在开发工具中看到正确的svg标记,但浏览器没有显示它。 请查看实时示例
这是该指令:
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>'
      };
    }
  );

1个回答

8
这是由于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文档中提到。 - Chris Nicola
1
注意:这也适用于引用常规svg文件的templateUrl:。svg文件也可以包含Angular指令,甚至是ng-transclude。干得好! - Joe Beuckman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接