How to modify chartjs tooltip to add customized attribute

独自空忆成欢 提交于 2019-12-25 14:00:46

问题


How I have to edit the tooltip template that i can add customized attributes from my json file ? Below the example:

ChartJS Example

In the x-axis are the Months with the first letter, but in the tooltip i want to show the first three letters of the month - How can i do this ?

EDIT: My JSON File:

{"modules":[{
"name":"Chart 1",
"link":"www.google.com",
"type":"Bar",
"series":"SeriesA",
"data":[[20,40,50,40,20,20,20,20,20,20,20,20]],
"labels":["M","J","J","A","S","O","N","D","J","F","M","A","M"],
"colors":[{
    "fillColor":"blue"
    }],
"options":{
    "scaleShowGridLines":false
    }

    }]}

回答1:


Different Labels in Tooltip vs Scale

Just use the tooltipTemplate option

Preview


Script

function Label(short, long) {
  this.short = short;
  this.long = long
}
Label.prototype.toString = function() {
  return this.short;
}

var data = {
    labels: [ 
      new Label("J", "JAN"), 
      new Label("F", "FEB"), 
      new Label("M", "MAR"),
      new Label("A", "APR"),
      new Label("M", "MAY"),
      new Label("J", "JUN"),
      new Label("J", "JUL")
    ],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};

// create chart
var ctx = document.getElementById("chart").getContext('2d');
new Chart(ctx).Bar(data, {
  tooltipTemplate: "<%if (label){%><%=label.long%>: <%}%><%= value %>",
});


Fiddle - https://jsfiddle.net/7z1s1feg/




回答2:


This part of the documentation explain you how to extend the tooltips elements.

var myPieChart = new Chart(ctx).Pie(data, {
    customTooltips: function(tooltip) {

    };
});

Plus, this example show you how to modify the HTML of the tooltip inside this function. The example from GitHub :

var innerHtml = '';
    for (var i = tooltip.labels.length - 1; i >= 0; i--) {
        innerHtml += [
            '<div class="chartjs-tooltip-section">',
            '   <span class="chartjs-tooltip-key" style="background-color:' + tooltip.legendColors[i].fill + '"></span>',
            '   <span class="chartjs-tooltip-value">' + tooltip.labels[i] + '</span>',
            '</div>'
        ].join('');
    }
    tooltipEl.html(innerHtml);

With these elements, you will be able to customize your tooltips however you want.



来源:https://stackoverflow.com/questions/34138456/how-to-modify-chartjs-tooltip-to-add-customized-attribute

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