Kuan Kuan - 5 months ago 45
AngularJS Question

Why template rendering get error for SVG element in ANgular



<html ng-app="vg">

<body>

<justsvg width="100" height="25"></justsvg>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('vg', []);
app
.directive("justsvg", function(){
return {
restrict:"AE",
scope:{
width: "@",
height: "@"
},
template: "<svg width='{{width}}' height='{{height}}'></svg>"
}
})

</script>


</body>

</html>





ALl:

I am pretty new to Angular, when i try to render SVG in a directive, it keeps giving me error like:

<svg> attribute width: Expected length, "{{width}}".


My code is pretty simple:

.directive("justsvg", function(d3){
return {
restrict:"AE",
scope:{
width: "@",
height: "@"
},
template: "<svg width='{{width}}' height='{{height}}'></svg>"
}
})


The way I use it is:

<justsvg data=data width="100" height="25"></justsvg>


I wonder why even this simple usage still gets error? And also, could anyone show me how to debug this kinda error?

And interesting thing is: even I got this error, the SVG still can get rendered correctly

Answer

Change your = to @.

= - is a two-way binding. You must to pass a variable
@ - is a one way binding. You pass a text to it.

and put your width's and height's values into '.

.directive("justsvg", function(d3){
    return {
        restrict:"AE",
        scope:{
            data: "=",
            width: "@",
            height: "@"
        },
        template: "<svg></svg>",
        link: function ($scope, $element) {
                $element.attr('width', $scope.width);
                $element.attr('height', $scope.height);
        }
    }
})

And in the function you have a parameter with the name d3.If it is not an service you have defined, remove it.It also can make an error.

Comments