且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将外部JSON加载到ChartJs中

更新时间:2022-06-02 22:02:08

如果要使用从data.json返回的JSON,则需要在回调函数中执行以下操作:

If you want to use the returned JSON from data.json you need to do this in the callback function like this:

$.getJSON("data.json", function (json) {
  // will generate array with ['Monday', 'Tuesday', 'Wednesday']
  var labels = json.map(function(item) {
    return item.timestamp;
  });

  var data = {
    labels: labels,
    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]
    },
    {
      label: "My Second dataset",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",
      highlightFill: "rgba(151,187,205,0.75)",
      highlightStroke: "rgba(151,187,205,1)",
      data: [28, 48, 40, 19, 86, 27, 90]
    }
    ]
  };

  var ctx = document.getElementById("myChart").getContext("2d");
  ctx.canvas.width = 1000;
  ctx.canvas.height = 800;

  var myChart = new Chart(ctx).Bar(data);
});

如果将它与Angular一起使用,我建议使用angular chart.js版本,请参见: http://jtblin.github.io/angular-chart.js/

If you are using it with Angular I would recommend using the angular chart.js version, see: http://jtblin.github.io/angular-chart.js/

那么您已经有了一个可以使用的角度指令!

Then you already have an angular directive, which you can use!