user3632710 user3632710 - 3 months ago 29
Javascript Question

AngularJS not rendering SVG correctly

I have a directive that should append a SVG element to the directive element

.directive('aSvg', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {
var svgTag = angular.element('<svg viewBox="0 0 4000 2000" version="1.1"><defs><marker id="StartMarker" viewBox="0 0 12 12" refX="12" refY="6" markerWidth="3" markerHeight="3" stroke="green" stroke-width="2" fill="none" orient="auto"><circle cx="6" cy="6" r="5"></circle></marker><marker id="MidMarker" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="strokeWidth" markerWidth="3" markerHeight="3" stroke="lightblue" stroke-width="2" fill="none" orient="auto"><path d="M 0 0 L 10 10 M 0 10 L 10 0"></path></marker><marker id="EndMarker" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="strokeWidth" markerWidth="3" markerHeight="3" stroke="red" stroke-width="2" fill="none"><rect x="0" y="0" width="10" height="10"></rect></marker></defs><path d="M 200 250 L 700 100 L 900 350 L 1200 400 L 1300 200 L 1700 680 L 2200 680 L 2600 400" fill="none" stroke="black" stroke-width="50" marker-start="url(#StartMarker)" marker-mid="url(#MidMarker)" marker-end="url(#EndMarker)"></path><path d="M 1000 750 S 2000 750 2500 1250 S 1200 1000 1300 1400 S 1700 1480 1900 1200" fill="none" stroke="tomato" stroke-width="50" marker-start="url(#StartMarker)" marker-mid="url(#MidMarker)" marker-end="url(#EndMarker)"></path></svg>');
$compile(svgTag)(scope);
angular.element(svtTag).appendTo(element[0]);
}
};
});


And in html I have the directive as an element:

<body>
<div>
<a-svg></a-svg>
</div>
</body>


However the SVG is not rendering correctly, only the 2 lines (black and orange) appear but there are no markers rendered. The SVG used in the example seems to be correct, because it renders correctly if I save it to a file, but for some reason it's not working in AngularJS.

What am I missing here?

Thanks in advance.

Edit 1: I was using AngularJS v1.2.20, I tried with v1.3.0 but still have the same problem.

Answer

After more researching I found out that the problem was in Angular routing, more specifically in the <base href='/'> tag that was messing around with the links defined in the SVG markers.

I solved my problem by changing the url in the markers attributes of each path (note the /myroute in the marker-start, marker-mid and marker-end attributes):

<path d="M 200 250 L 700 100 L 900 350 L 1200 400 L 1300 200 L 1700 680 L 2200 680 L 2600 400" fill="none" stroke="black" stroke-width="50" marker-start="url(/myroute#StartMarker)" marker-mid="url(/myroute#MidMarker)" marker-end="url(/myroute#EndMarker)"></path>

For more details, I suggest reading the accepted answer for the question here.

Comments