0

I have a form in an AngularJS application that, when submitted, asynchronously grabs json from a server and displays it on the screen.

I'd like to add a second button to the form, so that when it is clicked, the form takes the json from the server, converts it to csv format, and downloads it to the computer who click that button.

My current controller code looks like this:

angular.module('myApp')
  .controller('QueryCtrl', ['$scope', 'Query', function ($scope, Query) {
    $scope.onSubmit = function() {
      var json = $.post('http://localhost:3000/api/query', { 'input': $scope.query_box });
      json.done(function(result){
         $scope.queries = result;
         $scope.$apply();
      })
    };
  }
])

I'd like to add another event handler function that is almost exactly the same, but instead of changing the value of $scope.queries, it will instead put the result data into a csv file for download. Something like (warning: pseudocode):

    $scope.csvSubmit = function() {
      var json = $.post('http://localhost:3000/api/query', { 'input': $scope.query_box });
      json.done(function(result){
         my_csv = createCSV();
         download(my_csv);
      })
    };

How can I accomplish this?

Huangism
  • 16,278
  • 7
  • 48
  • 74
johncorser
  • 9,262
  • 17
  • 57
  • 102
  • Take a look at those threads: http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server and http://stackoverflow.com/questions/2897619/using-html5-javascript-to-generate-and-save-a-file . I don't think there is a easy (and good) solution to do this. The best is to request again the data from the server, and let the server format it. – Christian Benseler Jul 30 '14 at 18:18
  • 1
    You *also* could create a data URI from your JSON, apply it to a fake `a` element, and then trigger a click on it. Perk: no additional server transaction needed! – Casey Falk Jul 30 '14 at 18:21
  • I like this idea! How can I make a data uri that downloads a file? – johncorser Jul 30 '14 at 18:42

0 Answers0