Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I use AngularJS directive in svg the result is not presented

Tags:

angularjs

svg

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>'
      };
    }
  );
like image 299
Ido Ran Avatar asked Feb 15 '23 18:02

Ido Ran


1 Answers

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

like image 118
Ashley Davis Avatar answered May 05 '23 05:05

Ashley Davis