如何在运行时添加SVG元素 - Angular

Sam*_*ami 11 javascript svg angularjs

我将通过单击按钮添加SVG元素:

myApp.directive('addRectangle', function() {
    return function(scope, element, attr) {
        element.bind('click',function() {
            scope.rectCount++;
            angular.element(document.getElementsByClassName('svgMain')).append('<circle r=5 cx=200 cy=200 fill=red data-scope='+scope.rectCount +' />');


        });
    }
});
Run Code Online (Sandbox Code Playgroud)

该元素将按照我的预期正确添加,但问题是它没有显示在相关位置!我已经检查了页面的源html,我完全确定了.这是这个问题的小提琴:jsfiddle

另外,我正在使用angular版本1.4.x.

Gab*_*iel 5

正如@RobertLongson在问题的评论中所说,你应该SVG在每次想要添加新SVG元素时提及命名空间,例如:

function makeSVG(tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }
Run Code Online (Sandbox Code Playgroud)

您可以使用此功能添加新SVG元素.我也更新了小提琴.