title: Angular.js generate csv file from json data
body: <p>I am trying to generate a csv file from json data using Angular.js.</p>
  
  <p>When I get the data from my server, the user sees it in a table and can use various filters on the data. When the user filters it as desired, I want them to be able to create a csv report.</p>
  
  <p>Instead of sending the filters back to the server to generate the file. I would like to do it directly from the filtered data in Angular.</p>
  
  <p>Right now, I have this:</p>
  
  <pre><code>$scope.getReport = -&gt;
        filteredItems = $filter('filter')($scope.records, $scope.query)
        filteredItems = $filter('orderBy')(filteredItems, $scope.tableSort.getOrderProp())
  
        csvRows = []
        csvRows.push('Title,Assigned ID,Last Name,First Name,Start Date,Complete Date,Page,Test Progress,Certificate')
  
        csvRows.push("#{record.course.title},#{record.course.assigned_id},#{record.user.last},#{record.user.first},#{record.start_date},#{record.complete_date},#{record.page},#{record.test_progress},#{record.get_cert}") for record in filteredItems
        csvString = csvRows.join("\r\n");
  
        report = document.createElement('a')
        angular.element(report)
          .attr('href', 'data:application/csv;charset=utf-8,' + encodeURI csvString)
          .attr('download', 'report.csv')
        console.log(report)
        document.body.appendChild(report);
        report.click();
  </code></pre>
  
  <p>It's a bit messy, but it seems to work in Firefox and Chrome. I need something that will work in IE9+ as well.</p>
  
  <p>Another option I was thinking, but I can't figure out how to do would be to use a form and send the json data to the server. I can then have the server respond with a CSV file. My problem here is that I don't know how to get the json data to the server without using Ajax which won't download the file returned.</p>
  
  <h2>Update</h2>
  
  <p>I don't think it's the best method, but I am using a combination of my two solutions. I have javascript create the CSV like above. Then when I submit a form, it adds the 'csvString' as the value of a hidden form input. The data goes to the server which just responds with a csv file.</p>
  
  <h2>Update 2</h2>
  
  <p>Again, this method seems to not work in IE...</p>