user3378649
user3378649

Reputation: 5354

How to load CSV File in Angular JS to do charts

I am working to read a CSV File in AngularJS, then create a chart using the data from the CSV.

CSV file

Date,Energy
2001,0.851
2002,0.841
2003,1.000
2004,0.984
2005,1.006
2006,2.769
2007,2.791

I use this code to transform the CSV file into data objects

var Mymodule = angular.module('Mymodule', []);
Mymodule.factory('Items', ['$http', function($http){
  var Url   =  "data/ex.csv";
  var Items = $http.get(Url).then(function(response){
    return csvParser(response.data);
  });
  return Items;
}]);

Here is chart I use (on jsfiddle)

Now I have problems getting the data from the function that transforms the CSV to the function that makes charts. Inspired this thread thread, I tried using injectors but it didn't work out.

Here is what I tried.

var $injector = angular.injector(["ng", "MyModule"]);
$injector.invoke(['Items', function(Items){ 
  /* do stuff */ 
  console.log(Items);  // e.g. print the Items
}]);

I also tried using d3.csv with a global variable:

var rows;
d3.csv("path/to/file.csv", function(rows) {
  doSomethingWithRows(rows);
});

function doSomethingWithRows(rows) {
  // USE AngularJS Chart
}

My question: how can I load a CSV file and get the data to angularjs-chart to build my chart?

Upvotes: 3

Views: 6062

Answers (1)

user1563700
user1563700

Reputation:

If you say var a = b; then variable a gets the result of b. The result of $http.get().then... is not your items, since your items are not loaded yet. If you use a promise and call .then(function(x) {return x} the value x is returned to nowhere.

You can achieve what you want by doing this:

var Mymodule = angular.module('Mymodule', []);
Mymodule.factory('Items', ['$http', '$q', function($http, $q){
  var Url   =  "data/ex.csv";
  
  var ItemsDefer = $q.defer()
  $http.get(Url).then(function(response){
     ItemsDefer.resolve(csvParser(response.data));
  });
  return ItemsDefer.promise;
}]);

Mymodule.controller('Charts', ['$scope', 'Items', function($scope, Items) {
     Items.then(function(parsedCsvData) {
         $scope.chartData = parsedCsvData;
         $scope.initChart();
     });
});

And this great video by John Lindquist explaining angularjs promises can help you.

Upvotes: 1

Related Questions