访问已创建的Chart.js图表 [英] Getting access to already created Chart.js chart

查看:105
本文介绍了访问已创建的Chart.js图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这样的角度图创建了一个BarChart:

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>

我写了一个 chartClick 函数基于一些例子看起来像这样:

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

我的问题是:我如何获得对我创建的图表的访问权限将它分配给 myBarChart

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

我找到了 Highcharts 但我无法找到 Chart.js

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

更新:

根据@IBarros提供的链接,我设法编写以下几行代码:

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

我有2个图表 - 一个饼图,一个条形图。更重要的是,每个图表可以多次发出事件,因此我在控制台中打印了7个图表。我的下一个问题是:如何找出我正在寻找的条形图是什么?

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?

推荐答案

之所以如此在本期中解释了7次触发事件:如何获取图表实例? #464

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.

要找出您想要的图表对象,只需查看图表指令ID(或图表)在图表对象中输入。

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.

将对象用作关联数组

$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;
});

按指令ID访问图表对象

Access chart object by its directive id

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

这篇关于访问已创建的Chart.js图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆