4

我正在尝试创建将在 svg 元素中使用的 AngularJS 指令。
该指令不创建 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>'
      };
    }
  );
4

1 回答 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

于 2014-01-19T07:08:19.863 回答