Ajit Hegde Ajit Hegde - 6 months ago 35
AngularJS Question

Save json to file in angularjs..?

I am new to angularjs and trying create an single page application. I have a home controller with very simple code. It has one button "Get Data" which calls the api and api returns a json data.

Now I got the response and I can display the response on html page.
The json data is like this


Now my problem is
How can I save the above JSON data to pc when I click the button "Get Data" ?

$scope.saveToPc = function (data, filename) {

  if (!data) {
    console.error('No data');

  if (!filename) {
    filename = 'download.json';

  if (typeof data === 'object') {
    data = JSON.stringify(data, undefined, 2);

  var blob = new Blob([data], {type: 'text/json'});

  // FOR IE:

  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, filename);
      var e = document.createEvent('MouseEvents'),
          a = document.createElement('a');

      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
      e.initEvent('click', true, false, window,
          0, 0, 0, 0, 0, false, false, false, false, 0, null);

The solution is shamelessly copied from http://bgrins.github.io/devtools-snippets/#console-save

Edit Thanks to @ufk changed deprecated method initMouseEvent to initEvent. Don't know why it doesn't work in MSIE 11, probably due to security restrictions. And Microsoft Edge has new way to set all the properties of the synthetic event, but I haven't tested it.