[Chartjs]-Getting access to already created Chart.js chart

4👍

The reason why the event is fired 7 times was explained in this issue: How to get chart instance? #464

If options or other optional attributes are set after the data is set
the chart will be destroyed and recreated. This logic is what allows
the chart to be automatically updated everytime something changes in
the chart settings.

When that happens you should just update the reference on your side.

To figure out which chart object is the one you want, just look for the chart directive id (or chart type) in the chart object.

Example:

Use an object as an associative array

$scope.myCharts = {};

Save object reference in the associative array

$scope.$on('chart-create', function (event, chart) {
    console.log(chart.chart.canvas.id);
    console.log(chart.chart.config.type);
    //If id is the same, reference will be updated
    $scope.myCharts[chart.chart.canvas.id] = chart;
});

Access chart object by its directive id

console.log($scope.myCharts[id]);

Leave a comment