Shai UI
Shai UI

Reputation: 51928

How to programmatically ng-bind a property on an svg element?

I'd like to bind a background color to an svg element. I have an external svg file that I'm referencing, myfile.svg, inside of this file there's a circle with the id 'mycircle'.

So my html looks like:

<div ng-controller="MyCtrl">
<embed src="myfile.svg" id="mySvg"/>
</div>

I have a controller that looks like:

function MyCtrl($scope) {
   $scope.myfill = 'yellow';   
}

Now I'd like to set up the binding programmatically, this is what I do:

var mySvg = document.getElementById("mySvg");
mySvg.addEventListener("load", function() {
    var svg = mySvg.getSVGDocument();
    var mycircle = svg.getElementById("mycircle");

    //this works:
    //mycircle.setAttribute("fill", "yellow");            

    $(mycircle).attr('ng-bind','myfill');
});

However, this doesn't set the fill. I'm thinking I might need to use angular "compile" or something in order to get this to work (?) can anyone clue me in on how to do this?

Upvotes: 0

Views: 704

Answers (1)

Bharat
Bharat

Reputation: 943

Yes you need to compile. Should bind as an exp and compile against the scope. Below snippet should work.

var mySvg = document.getElementById("mySvg");
mySvg.addEventListener("load", function() {
    var svg = mySvg.getSVGDocument();
    var mycircle = angular.element(svg.getElementById("mycircle"));
    mycircle.attr('fill', '{{myfill}}');
    $compile(mycircle)($scope);
});

Upvotes: 1

Related Questions