0

I am trying to load new data (to hide specific graph), I tried destroy() function like here but it's not working, I did't know what I am missing.

I want to load one data (of two) but I want to select which one to visible.

HTML

<canvas id="linechart"></canvas>
<div>
  <a id="current">Current</a>
  <a id="forecast">Forecast</a>
</div>

JavaScript

$(document).ready(function(){
    var canvas = document.getElementById('linechart');
    var ctx = canvas.getContext('2d');
    var current = [800, 1350, 1400, 1600, 2600, 3100];
    var forecast = [400, 1050, 1200, 1300, 1800, 2400];
    var data = {
      labels: ["2", "4", "8", "12", "16", "20"],
      pointDotRadius: 0,
      pointRadius: 0,
      pointBorderWidth : 0,
      pointHitRadius: 0,
      datasets: [
      {
        label: "current",
        fillColor: "rgba(220,220,220,0)",
        strokeColor: "#7bc775",
        pointColor: "#7bc775",
        data: current,
      },
      {
        label: "forecast",
        fillColor: "rgba(151,187,205,0)",
        strokeColor: "#fed477",
        pointColor: "#fed477",
        data: forecast,
      }]
    };
    var myLineChart = new Chart(ctx, {
      type: 'line',
      data: data
    });
    var step  = 800;
    var max   = 3200;
    var start = 0;
    window.myObjBar = new Chart(ctx).Line(data, {
      scaleOverride: true,
      scaleSteps: Math.ceil((max-start)/step),
      scaleStepWidth: step,
      scaleStartValue: start,
      responsive : true
    });
    $('#current').click(function(){
      current = [];
      if(myLineChart!== null){
        myLineChart.destroy();
        myLineChart = new Chart(ctx, {
          type: 'line',
          data: data
        });
      }
    });
  });

Fiddle Link

Community
  • 1
  • 1
Madan Bhandari
  • 2,094
  • 2
  • 26
  • 46
  • Did you actually try `.distroy()`, as you mentioned in your question, instead of `.destroy()` ? -- **Edit :** Nevermind, I just saw your fiddle – tektiv Jun 28 '16 at 12:22
  • Sorry, that was typo. I actually use destroy(), you can check code on fiddle too. – Madan Bhandari Jun 28 '16 at 12:26
  • You might find [chartNew.js](https://github.com/FVANCOP/ChartNew.js) easier to work with -- it's just like chart.js except that the api works as documented. – cssyphus Jun 28 '16 at 13:04

1 Answers1

1

I found a solution to your problem using an up to date version of Charts.js

Using destroy and storing your datas in an array. When you click on the control, it destroys the chart and rebuild a new one with the selected data

var mychart = new Chart(ctx,config);
$('.selector').click(function(){
 data.datasets = [datasets[$(this).data('index')]];
 if(mychart!== null){
      mychart.destroy();
      mychart = new Chart(ctx, config);
 }
 });

See the updated fiddle here : https://jsfiddle.net/3563ko2t/6/

Sladix
  • 712
  • 2
  • 7
  • 19