Getting access to already created Chart.js chart

佐手、 提交于 2019-12-13 14:44:22

问题


I have created a BarChart with angular-chart like this:

<canvas id="bar" 
 chart-data="ctrl.barChartData" 
 chart-options="ctrl.barChartOptions" 
 chart-labels="ctrl.barChartLabels" 
 chart-series="ctrl.barChartSeries" 
 chart-click="ctrl.chartClick" 
 class="chart chart-bar">
</canvas>

I have wrote a chartClick function based on some example and looks like this:

vm.chartClick = function(evt){
        var myBarChart = //how I can obtain a access to my created bar chart?
        var activePoints = myBarChart.getPointsAtEvent(evt);
        console.log("active: "+activePoints);
}

My question is: how can I obtain an access to chart I have created and assign it to myBarChart?

I have found solution for Highcharts however I can't find it for Chart.js

UPDATE:

Based on link provided by @IBarros I have manage to wrote following few lines of code:

$scope.$on('chart-create', function (event, chart) {
    //console.log(chart);
    myBarChart = chart;
});

I have 2 charts - one pie chart, one bar chart. What is more the event can be emitted multiple times for each chart so as a result I have a 7 charts printed into console. My next question is: how to find out what chart is a bar chart I'm looking for?


回答1:


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]);


来源:https://stackoverflow.com/questions/41545742/getting-access-to-already-created-chart-js-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!