【问题标题】:When I use AngularJS directive in svg the result is not presented当我在 svg 中使用 AngularJS 指令时,不会显示结果
【发布时间】:2013-11-15 16:15:16
【问题描述】:

我正在尝试创建将在 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>'
      };
    }
  );

【问题讨论】:

标签: angularjs svg


【解决方案1】:

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

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

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 文件的 templateUrl:。 svg 文件也可以包含角度指令,甚至是 ng-transclude。干得好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
相关资源
最近更新 更多