Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a SVG element at runtime - Angular

I'm going to add a SVG element by clicking a button:

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 +' />');


        });
    }
});

The element will be added correctly as I expect, but the problem is it is not showing in the related position! I've checked the source html of the page and I'm completely sure about that. This is the fiddle of this question: jsfiddle

In addition, I'm using angular version 1.4.x.

like image 823
Saman Gholami Avatar asked Aug 17 '15 15:08

Saman Gholami


1 Answers

As @RobertLongson said in the comment of the question you should mention SVG namespace in each and every time you want to add a new SVG element, like this sample:

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;
        }

You can use this function in order to add a new SVG element. Also I've updated the fiddle.

like image 141
Gabriel Avatar answered Oct 09 '22 21:10

Gabriel