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.

推荐答案

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

不是的.即使您正在从本地文件系统(例如,file://myfile.html)或本地Web服务器(例如,http://localhost/myfile.htmlhttp://host-on-my-intranet/myfile.html)运行页面,您仍然无法从浏览器托管的JavaScript代码直接写入文件.

Two choices:

  1. 将其发送到可以将其写出的某个地方(例如,服务器),或者

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

第2条中的Full Example条:

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

Json相关问答推荐

使用Powershell脚本将配置信息块添加到json文件

使用Jolt变换转换JsonArray以将关键字转移到内部JsonArray中

Python将Pandas转换为嵌套的JSON

Jolt变换将字段移动到数组的每个元素中

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

Android 如何判断小时时间是否在两个时间之间?

如何在 jq 中按 IP 地址排序?

MarkLogic REST 资源 API - 仅使用一个 POST 请求修补多个文档

如何在 Dart 中与多个 map (字典)相交

Powershell中等效的JSONPath通配符以 Select 对象中的所有数组

如果 JSON 对象包含列表中的子字符串,则丢弃它们

如何用 Xidel 正确读取这个 JSON 文件?

如何解决名为 null 的map值

如何使用 Serde 使用顶级数组反序列化 JSON?

在 bash 中将 CSV 转换为 JSON

按 JSON 数据类型 postgres 排序

如何在已声明的 JSON 对象中添加键值对

如何将有向无环图 (DAG) 存储为 JSON?

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

YAML 将 5e-6 加载为字符串而不是数字