Reputation: 707
After creating a chart like this (with Chart.js, latest version):
var ctx = $('#graph');
var graph = new Chart(ctx, {
type: 'line',
data: someData,
});
I would like to retrieve the Chart object in another function in order to add some data point to it:
var graph = ???
graph.data.labels.push(1)
graph.data.datasets[0].data.push(10);
How do I get the Chart object?
Thank you in advance!
Upvotes: 14
Views: 26330
Reputation: 598
You can just do this:
var graph = Chart.getChart('graph')
Works in v3 - not sure when it was introduced.
Upvotes: 11
Reputation: 5849
Perhaps:
var ctx = $('#graph');
var graph = new Chart(ctx, {
type: 'line',
data: someData,
});
ctx.data('graph', graph);
and later:
var graph = $('#graph').data('graph');
graph.data.labels.push(1)
graph.data.datasets[0].data.push(10);
graph.update();
// //
Upvotes: 10
Reputation: 1611
//get object
const chartJS: Chart = $("#myChart").data('chart');
//change something
chartJS.config.options.scales.yAxes[0].ticks.min = minVal <= 0 ? minVal : minVal -
//update
chartJS.update();
Upvotes: 2
Reputation: 32889
You could directly use the graph
object without assigning it to another variable ( considering graph
is a global variable ) to add any sort of data from another function.
Here is a quick example of that ...
var ctx = $('#graph');
var graph = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
label: "Sales",
data: [1, 2, 3, 4, 5],
fill: false,
borderColor: '#07C',
}]
}
});
function addData() {
graph.data.labels.push('June')
graph.data.datasets[0].data.push(6);
graph.update();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="addData()">Add Data</button>
<canvas id="graph"></canvas>
in case: the graph
variable is inside a function then, you'd have to make the variable global to use it from another function
Upvotes: 3