I'm trying to create AngularJS directive that I will use inside svg element.
The directive do not create svg element but use exist one.
I can see the right svg markup in the dev-tools but the browser does not display it.
Please see live example.
This is the directive:
angular.module('ui.directives', []).directive('svgText',
function() {
return {
restrict: 'E',
replace: true,
template: '<text fill="green" x="4" y="20" font-weight="bolder" font-size="2" font-family="Arial">89</text>'
};
}
);
This happens because jQuery (which AngularJS uses under the hood) doesn't know how to create svg elements. You can workaround this by adding a link function to the directive that clones the element that was created but creates it in the SVG namespace.
A potentially better method is to wrap your template in an SVG element (with namespace defined) and then in the link function pull out the child element and use that, it will already be created in the correct namespace.
module.directive(
'svgText',
function () {
return {
restrict: 'E',
template: '<svg xmlns="http://www.w3.org/2000/svg"><text fill="green" x="4" y="20" font-weight="bolder" font-size="2" font-family="Arial">89</text></svg>',
replace: true,
link: function (scope, elem, attrs) {
// Extract the child element to replace the SVG element.
var child = angular.element(elem[0].firstElementChild);
// Copy attributes into element.
for (attrName in attrs) {
if(typeof attrs[attrName] === "string") {
child.attr(attrName, attrs[attrName]);
}
}
elem.replaceWith(child );
}
};
}
);
I have published an article on AngularJS + SVG which talks through many such issues.
http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With