Chart.js HTML custom legend issues with doughnut c

2019-06-28 04:33发布

问题:

I'm working with chart.js and I followed this to create a custom HTML legend. The thing is, the hide/show functionality is not working. The first legend click hides the whole chart, while the others produce the error:

Uncaught TypeError: Cannot read property '_meta' of undefined
    at t.getDatasetMeta (Chart.min.self-b26766dbef822c075056eb7012dc36ae75970dc990497732f927d46ef6070858.js:11)
    at HTMLLIElement.legendClickCallback (plot.self-416475a747a420b91c7fab454c07846f1043f55cc28f6d810fafeab61c56cf01.js:317)

so it traces back to t.getDatasetMeta. I gotta say it's working great with line/bar charts, so its only my doughnut chart which breaks. Let me know if you need more info. Oh and thanks :P

EDIT: fiddle

回答1:

The problem is that you have only one dataset and your code use the index of legend item clicked to hide datasets[index].

On the contrary you need to hide single item data as below:

var meta = chart.getDatasetMeta(0);
var item = meta.data[index];

Check the fiddle updated: https://jsfiddle.net/beaver71/aa2n39s2/