ChartJS: Update tooltip

依然范特西╮ 提交于 2021-01-28 14:53:03

问题


I'm having a chart build with ChartJS. I'm including datasets.label in multipleTooltipLabel template and facing an update issue. When changing a datasets.label and running chart.update() the tooltip is not updated. I created a JSFiddle demonstrating the issue.

The code I use to include datasets label in tooltip:

var options = {
  multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>"
};

Beside that option I followed ChartJS usage example for Line charts.

Change label and update chart:

myNewChart.datasets[0].label = 'updated label';
myNewChart.update();

Label shown in tooltip is not updated...

I had a look in ChartJS source code and figured out that showTooltip function is called with a ChartElements array which was not updated.

Update: I might cached the issue. label of dataset is set on each point element and not updated if it changes. showTooltip used this "cached" dataset label when drawing a tooltip. Perhaps this should not be a question on StackOverflow but a bug report for ChartJS.


回答1:


I found a solution:

myNewChart.datasets[0].points.forEach(function(point) {
  point.datasetLabel = 'updated label';
});

This might also be the way it should be done. Chart.js documentation of update method says you should set myLineChart.datasets[0].points[2].value = 50; to change the value. That's confusing cause on creation dataset expects the values in data property. points is generated by Chart.Line Class on init. Naming may be different for other chart types (eg. it's bars for a bar chart).

I'm not quite sure if myLineChart.datasets[0].label value is used somewhere or if could be unchanged.




回答2:


I could solve your problem by changing the original data object (data.datasets[0].label='updated label') then running myNewChart.initialize(data).



来源:https://stackoverflow.com/questions/35892226/chartjs-update-tooltip

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