m9_psy
m9_psy

Reputation: 3386

How to append svg element within an AngularJS directive?

I am using element.append method, but nothing appears on the screen. Seems that svg doesnt render elements if I use this method. Here is example.

app.directive('dir',  function($document){
    return{
        restrict: "A",
        link: function(scope, element, attr)
        {
            scope.add_circle = function (){
               var area = angular.element( document.querySelector("#draw_area") );
               area.append("<circle cx=50 cy=50 r=10 fill='red'></circle>");
                alert("Circle appended!")
            };
        }
}
});

Upvotes: 2

Views: 1872

Answers (1)

m9_psy
m9_psy

Reputation: 3386

After i looked some answers about this, I edited my code to:

app.directive('dir',  function($document){
return{
    restrict: "A",
    link: function(scope, element, attr)
    {
        scope.add_circle = function (){
           var area = angular.element( document.querySelector("#draw_area") );
           var namespace = "http://www.w3.org/2000/svg";
           var name = "circle";
           var attributes = {cx: 50, cy:50, r:10, fill: 'red'};
           var svg_element = document.createElementNS(namespace, name);
           for (var attr in attributes)
               svg_element.setAttribute(attr, attributes[attr])
           area.append(svg_element);
            alert("Circle appended!")
        };
    }

} });

Here is good answer about this issue.

Upvotes: 2

Related Questions