1

I try to draw a chart using Chart.js. The data comes from my API and I know the format is OK. I don't know how to pass the data retieved from the API to the javascript function.

In my controller, I got:

$http.get('/api/bilan').then(function(result) {
  $scope.finances = result.data;
});

And here is a snippet from where I should pass data:

var bilans = {
  labels: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
  datasets : [
    {
      data : [ TheDataFromTheApi ]
    }
  ]

};

What shoudl I put in TheDataFromTheApi? or how is the right way to do this?

1

2 Answers 2

1

Use the existing library of Chart.js which has already converted code in angularise way.

Just you need to include angular-chartjs.js

And then inject to your model angular.module('myApp', ['chart.js'])

After that you can use it as attribute anywhere you want.

HTML

<canvas class="chart chart-bar" data="bilans.data" labels="bilans.labels" series="bilans.series"></canvas>

CODE

var app = angular.module("Bar_Chart", ["chart.js", "ui.bootstrap"]);
app.controller('mainCtrl', function($scope,$http) {
    // you can get this data by ajax
    var TheDataFromTheApi = [1,2,3,4,5,6,7,8,9,10,11,12];
    $scope.bilans = {
      labels: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
      data: [TheDataFromTheApi],
      series:["Months"]
    };
});

Working Plunkr For your code.

Sign up to request clarification or add additional context in comments.

3 Comments

If I set var finances = result.data and try to use data: finances it doesn't work. I got finances is not defined
@LucienDubois updated sample code for your example and changed library, jtblin.github.io/angular-chart.js this is quite good than the first one..
I got an error: Cannot read property 'global' of undefined inangular-chart.js .. Hum
0

You should pass data into chart via an angular controller.

Call your service ($http.get ...) into the controller, and add its result in your data, then you may be able to create your charts.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.