Saman Gholami
Saman Gholami

Reputation: 3512

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.

Upvotes: 11

Views: 1951

Answers (1)

MR Zamani
MR Zamani

Reputation: 1423

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.

Upvotes: 5

Related Questions