11

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.

Saman Gholami
  • 3,416
  • 7
  • 30
  • 71
  • 1
    Presumably the append is putting data in the wrong namespace similar to this jquery issue http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element – Robert Longson Aug 17 '15 at 15:36
  • @RobertLongson I add xmlns="http://www.w3.org/2000/svg" attribute to both svg and circle element but there is no difference in the result. – Saman Gholami Aug 17 '15 at 15:42
  • There wouldn't be. You need to use createElementNS ideally or if not innerHtml will work in many (but not all UAs). – Robert Longson Aug 17 '15 at 15:50

1 Answers1

5

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.

Gabriel
  • 1,413
  • 1
  • 18
  • 29