Michael P.
Michael P.

Reputation: 1413

Angular.js and SVG-generating directive

I have a directive that references a template containing a simple SVG circle, which it adds to an SVG element. The output looks like this:

<svg version="1.1" baseProfile="full" width="100%" height="100%" fill="none" xmlns="http://www.w3.org/2000/svg">
  <circle r="50" stroke="#000" stroke-width="2" cx="100" cy="100" fill="#0ff" cursor="pointer" booth=""></circle>
</svg>

The problem is that the circle doesn't actually render in the browser; it's as though I never added the SVG at all. If I place this same HTML into the page by default, the circle renders as expected.

This is happening in all browsers in which I've tested the functionality (Chrome, Firefox, Safari).

Does anyone know what the problem might be?

Upvotes: 2

Views: 342

Answers (1)

Masklinn
Masklinn

Reputation: 64

The problem is that Angular directive adds your circle element as XHTML (with the namespace "http://www.w3.org/1999/xhtml") where it should be on the SVG namespace ("http://www.w3.org/2000/svg").

You can create your cirlce within your link function of your svg directive with the correct namespace, and append it.

template: '<svg></svg>',
link:  function(scope, element, attrs) {
    var myCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    angular.element(myCircle).attr('r', 50);
    angular.element(myCircle).attr('cx', 100);
    angular.element(myCircle).attr('cy', 100);
    element.append(myCircle);
}

Or you can use the D3 library to manipulate your svg elements within your angular directives, as explained in this video : https://www.youtube.com/watch?v=vmJ0501WzU0

Upvotes: 3

Related Questions