AngularJS:在指令中转换SVG元素

时间:2014-04-26 00:15:17

标签: angularjs svg angularjs-directive transclusion

我对通过组合Angular.js指令中包含的可重用图形元素来构建复合SVG感兴趣。例如,我可能有:

<div ng-app="svgApp">
  <canvas>
    <drawing ng-repeat="i in [1,2,3]" cy="{{i * 40}}"></drawing>
  </canvas>
</div>

我在哪里定义以下指令:

  .directive('canvas', function () {
    return {
      template: '<svg height=200 width=100 ng-transclude></svg>',
      restrict: 'E',
      replace: true,
      transclude: true
    };
  })

  .directive('drawing', function () {
    return {
      template: '<circle cx=50 r=15></circle>',
      restrict: 'E',
      replace: true
    };
  })

问题是SVG元素似乎没有被正确地转换。一条线索似乎是here, in another StackOverflow question,这主要是因为在Angular.js中没有正确创建SVG节点。

在进一步探索之后,我发现this solution, which involves using a helper function用正确创建的SVG节点替换相关的DOM元素,la:

  .value('createSVGNode', function(name, element, settings) {
      var namespace = 'http://www.w3.org/2000/svg';
      var node = document.createElementNS(namespace, name);
      for (var attribute in settings) {
        var value = settings[attribute];
        if (value !== null && !attribute.match(/\$/) && (typeof value !== 'string' || value !== '')) {
            node.setAttribute(attribute, value);
        }
      }
      return node;
  });

但是,我似乎不希望在任何地方都使用它,并且我希望尽可能将解决方法保持为本地错误,直到它被修复。

我的问题是以下是否是一个合理的解决方法:

angular.forEach(['circle', ...], function (svgElem) {

  svgModule

    .directive(svgElem, function (createSVGNode) {
      return {
        restrict: 'E',
        link: function(scope, element, attrs) {
          var node = createSVGNode(svgElem, element, attrs);
          angular.element(node).append(element[0].childNodes);
          element.replaceWith(node);
        }
      };
    });

});

这可以在Plunker中使用!

以这种方式重新定义现有的SVG元素指令对我有效吗?

1 个答案:

答案 0 :(得分:5)

如果您无法将代码移动到AngularJS 1.3的活动开发提示中,上面是一种可能的方法,其中转换不同命名空间(例如SVG或MathML)的元素的问题是resolved

链接的Plunker演示了如何使用修补程序更新代码。关键是增加了一个新的&#34; templateNamespace&#34;指令定义对象中的键:

  .directive('svgInternal', function () {
    return {
      templateNamespace: 'svg',
      template: '<g><rect height="25" width="25" /><text x="30" y="20">Hello, World</text></g>',
      restrict: 'E',
      replace: true
    };
  })

其中以下标记演示了正在使用的SVG类型指令:

  <svg height="30">
    <svg-internal></svg-internal>
  </svg>

修改:&#34;输入&#34;已更改为&#34; templateNamespace&#34;自1.3.beta.19。