Kuan Kuan - 6 months ago 18
AngularJS Question

Angular directive report error about SVG attribute while render it correctly

All:

When I tried to render a simple bubble chart with Angular, it keeps giving me error like:


jquery.min.js:3 Error: attribute cx: Expected length,
"{{d.cx}}".


But the render result is correct, I wonder how this happens and how to avoid those error?

My Code is like:



var app = angular.module("vp", []);
app
.controller("main", function($scope) {
$scope.data = [{
cx: 200,
cy: 200
}, {
cx: 100,
cy: 100
}]
})

<!DOCTYPE html>
<html ng-app="vp">

<head>
<title></title>
</head>

<body ng-controller="main">

<svg width="300" height="300">
<g>
<circle ng-repeat="d in data track by $index" cx="{{d.cx}}" cy="{{d.cy}}" fill="red" r="25"></circle>
</g>
</svg>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>



</body>

</html>




Answer

The problem is that the SVG gets rendered before Angular has bound the model values, and values of the form "{{d.cx}} are obviously not valid values.

The simplest solution is just to use ng-attr-xxx format for your SVG attributes.

ng-attr-cx="{{d.cx}}" ng-attr-cy="{{d.cy}}"

Then the real attributes won't get proper values till angular has executed its first digest.

You don't need to use a directive.