Search code examples
angularjshtmlangularjs-ng-repeatcanvasjs

Creating multiple CanvasJS charts inside <div> with ng-repeat


I am trying to create multiple CanvasJS charts inside a div.

The div expects array of data from controller, loops through it(using ng-repeat) and displays the data in various controls.

Now when I try to put a CanvasJS Chart inside this div, the chart does not render and the error I see is 'chart with id is not found'

But the same chart works well just outside this div.

Sample code here: http://jsfiddle.net/DTheWebDev/mozfsxpc/7/

APP.JS

var m = {
  "India": "2",
  "Australia": "3"
};

function MyCtrl($scope) {
  $scope.items = m;
}
var dps = [{
  x: 1,
  y: 10
}]; //dataPoints. 

var chart = new CanvasJS.Chart("chartContainer", {
  title: {
    text: "Live Data"
  },
  axisX: {
    title: "Axis X Title"
  },
  axisY: {
    title: "Units"
  },
  data: [{
    type: "line",
    dataPoints: dps
  }]
});

chart.render();
var xVal = dps.length - 1;
var yVal = 15;
var updateInterval = 1000;

var updateChart = function() {
  yVal = yVal + Math.round(5 + Math.random() * (-5 - 5));
  dps.push({
    x: xVal,
    y: yVal
  });
  xVal--;
  chart.render();

};
setInterval(function() {
  updateChart()
}, updateInterval);

HTML:

<h3>Match Summary:</h3>

<div ng-app ng-controller="MyCtrl">
  <div ng-repeat="(country,goals) in items">
    <div id="chartContainer" style="height: 200px; width: 100%;"></div>
    <h2>{{country}}: {{goals}} </h2>
  </div>
</div>

Tried to search with similar problem, but no luck.

Thanks for your time and help in advance.


Solution

  • The flow of the program should be taken care of. It throws the error 'Chart with ID is not found' as chart is tried to being rendered on a div element which doesn't exist yet. Also, the ids of different div elements should be different. You can use code similar to this to append dynamic id.

    <div ng-repeat="(country,goals) in items"> 
        <div id="chartContainer-{{country}}" style="height: 200px; width: 100%;"></div>
    <h2>{{country}}: {{goals}} </h2>
    </div>
    

    Here is the working jsfiddle