How to Write data to file in angularJS

牧云@^-^@ 提交于 2019-12-12 09:40:32

问题


I have a variable with huge data some thing like this.

$scope.employees = [
    {"firstName":"John", "lastName":"Doe",
      "city": "Bangalore","State":karnataka,},

    {"firstName":"Anna", "lastName":"Smith",
       "city": "Hyderabad","State":AndraPradesh,},

    {"firstName":"Peter", "lastName": "Jones",
      "city": "Mumbai","State":Maharastra,},
];

I want to save it to JSON file, when I click a button or something.


回答1:


$scope.employees is the object to be saved to a file

$scope.savedJSON = angular.toJson($scope.employees,true);
var blob = new Blob([$scope.savedJSON],{
   type: "application/json;charset=utf-8;"
});
var downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'sampleJSON.txt');
downloadLink.setAttribute('href', window.URL.createObjectURL(blob));
downloadLink.click();



回答2:


angular.toJson should help you out.

var app = angular.module('myApp', []);

app.controller('MainCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.employees = [
{"firstName":"John", "lastName":"Doe",
  "city": "Bangalore","State":karnataka,},

{"firstName":"Anna", "lastName":"Smith",
   "city": "Hyderabad","State":AndraPradesh,},

{"firstName":"Peter", "lastName": "Jones",
  "city": "Mumbai","State":Maharastra,},
];



$scope.savedJSON = '';

$scope.save = function () {
    $scope.savedJSON = angular.toJson($filter('filter')($scope.employees, $scope.searchText));
};
}]);

var blob = new Blob([scope.save],{
type: "application/json;charset=utf-8;"
});
downloadLink.attr('href', window.URL.createObjectURL(blob));


来源:https://stackoverflow.com/questions/28536265/how-to-write-data-to-file-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!