如何在angularJS中将数据写入文件

时间:2015-02-16 07:15:28

标签: json angularjs save writetofile

我有一个带有大量数据的变量,有些像这样。

$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,},
];

当我点击按钮或其他东西时,我想将它保存到JSON文件。

2 个答案:

答案 0 :(得分:3)

$ scope.employees是要保存到文件的对象

$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();

答案 1 :(得分:-1)

angular.toJson可以帮助你。

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));