如何在AngularJS中更新json文件中的数据

How to update data in a json file in AngularJS?

本文关键字:文件 数据 json 更新 AngularJS      更新时间:2023-09-26

我使用$resource.query()从JSON文件中获取JSON数组。我可以用$save更改数据,但JSON文件实际上并没有更新。在谷歌上搜了一上午也找不到解决办法。不确定是否可以用AngularJS更新本地json文件。任何帮助都会很感激。

这是我的代码。
getData: function(datatype){
    var url = "data/" + datatype + ".json";
    return $resource(url, {}, {
        query: {
            method: "GET",
            isArray: true
        }
    });
},

在另一个业务函数中调用getData()函数:

var post = this.getData("jobs").query(function(){               
    angular.forEach(staffs, function(staff){
        for(var i = 0; i < post.length; i++){
            if(post[i].id == jobId){
                alert(post[i].name); //Here it shows the original name "names and numbers"
                post[i].name = "changed";
                post[i].$save();    
                alert(post[i].name); //Here it shows the new name "changed"
                                     //but the data json file is not changed
                continue;
            }
        }
    });
});

jobs.json:

[
{
    "id": 554114, 
    "name": "names and numbers",  
    "facility_id": 0
},
...
]

上面Chris的回答似乎不切题。最初的问题是关于使用angular的$resource来保存。而不是javascript是否可以写入文件。

$resource已经定义了Post。因此,正确调用$resource.save()将对服务器进行post回调。在服务器上,您仍然需要编写代码来保存发布的数据。但底线是$resource允许Post。

shaosh似乎对$resource.save

有问题

post是您的资源。不是 post(我)

你不需要写

吗?
      post.$save(); 
$save() ?

这个Stackoverflow问题和答案可能对你有一些用处:

在短;Javascript通常不能写入文件,除非你要向服务器发送一个帖子,然后服务器可以更新你的json文件。