Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular directive report error about SVG attribute while render it correctly

Tags:

angularjs

svg

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>
like image 558
Kuan Avatar asked Feb 07 '23 21:02

Kuan


1 Answers

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.

like image 150
Paul LeBeau Avatar answered Feb 09 '23 10:02

Paul LeBeau