Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js replace all data

im having a issue with Chart.js.

Firts, I set a data, and then when a parameter change, I want rebind the entire chart. This work, but its like the chart with the old data still behind the new one.

first ->

chart.Line(data, options);

in a event ->

  chart.Line(newdata, options);

I saw this solution chart.js load totally new data

but I dont like this way. Im in a angular directive context, so it's not the best aproach.

I tried without results

.update( ), .removeData( ), .clear(), .destroy(), etc

here its my current directive

http://plnkr.co/edit/qn2UUyznonKm6zgEi8FW?p=catalogue

Any Idea ?

like image 762
Math Avatar asked Jun 12 '26 06:06

Math


2 Answers

You are creating a new chart, that's why you end up with the old chart behind the new one.

One simple option that I've used: Remove the old chart from the canvas that you are using for the chart:

$('#canvas').replaceWith('<canvas id="canvas"></canvas>');

And now create the chart with the new data in the same canvas

var ctxChart = document.getElementById("canvas").getContext("2d");
window.myChart = new Chart(ctxChart).Line(newdata, options);

Hope it helps!

like image 171
ednincer Avatar answered Jun 14 '26 21:06

ednincer


For those of you wondering the same thing with Pie charts, doesn't look like there's a given public method that works but you can use an easy workaround by removing the data yourself:

var pieChart = new Chart(ctx).Doughnut(undefined, pieChartOptions);
pieChart.segments.splice(0, pieChart.segments.length);

Seems to work ok, wish they would just add a remove all method or make the clear actually work.

like image 40
adameska Avatar answered Jun 14 '26 19:06

adameska



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!