Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write data to a locally json file with nothing but angular?

I'm trying to write data to a json file after hitting "Submit" on an html formly-form using only angular, but nothing is happening. I know I can read a json file using angular but not sure on creating files. onSubmit() in controller:

function onSubmit() {     $scope.save = function() {         $http.post('./temp/sample_data.json', JSON.stringify($scope.model)).then(function(data) {             $scope.msg = 'Data saved';         });     }; }; 

html:

<form name="form" ng-submit="onSubmit()" novalidate>     <formly-form model="model" fields="fields"></formly-form><br/>     <button type="submit">Submit</button> </form> 

The sample_data.json isn't created and if I create an empty file it does not fill up with the data as well. The $scope.model defenitly contains data. If anyone can help, it will be very appreciated. Thanks, Alon.

like image 418
Alon Weissfeld Avatar asked May 17 '15 14:05

Alon Weissfeld


People also ask

Does Angular use JSON?

JSON is used by Angular in a variety of contexts, including configuration. For example, the project generated by Angular CLI comprises many files with the . json extension, most notably the package. json and angular.

How do I run a local JSON file?

Chrome allows you to access local JSON or other data files if you launch it with the --allow-file-access-from-files flag. I checked this with the code above on version 34.0. 1847.131 m; it should work on other versions as well.


1 Answers

Is it possible to write data to a locally json file with nothing but angular?

No. Even if you're running the page from the local file system (e.g., file://myfile.html) or from a local webserver (e.g., http://localhost/myfile.html or http://host-on-my-intranet/myfile.html), you still have no means of directly writing to a file from browser-hosted JavaScript code.

Two choices:

  1. Send it to something (e.g., a server) that can write it out, or

  2. Provide it as a data: URI (if feasible in your case) that the user can right-click and choose "save as..."

    Here's how you create a data: URI for some JSON text:

    var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON); 

Full Example of #2:

var theData = {    foo: "bar"  };  var theJSON = JSON.stringify(theData);  var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);    var a = document.createElement('a');  a.href = uri;  a.innerHTML = "Right-click and choose 'save as...'";  document.body.appendChild(a);
like image 163
T.J. Crowder Avatar answered Sep 21 '22 05:09

T.J. Crowder