Save json for file in angularjs ..?

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

Now I got the answer, and I can display the answer on the html page. Json data is like this

{ "Name":"A", "Age":"21" } 

Now my problem is: How can I save the above JSON data on the PC when I click the β€œGet Data” button?

+8
json angularjs single-page-application
source share
1 answer
 $scope.saveToPc = function (data, filename) { if (!data) { console.error('No data'); return; } 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); } else{ 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); a.dispatchEvent(e); } }; 

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

Edit Thanks to @ufk, the deprecated initMouseEvent method has initMouseEvent to initEvent . I do not know why it does not work in MSIE 11, possibly due to security restrictions. And Microsoft Edge has a new way to set all the properties of a synthetic event, but I have not tested it.

+22
source share

All Articles