javascript 如何在 AngularJS 中更新 json 文件中的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24919636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update data in a json file in AngularJS?
提问by shaosh
I am using $resource.query() to fetch an JSON array from a JSON file. I can change the data with $save, but the JSON file is not actually updated. Can't find solutions after googling for the entire morning. Not sure if it is possible to update local json file with AngularJS. Any help would be appreciated.
我正在使用 $resource.query() 从 JSON 文件中获取 JSON 数组。我可以使用 $save 更改数据,但实际上并未更新 JSON 文件。在谷歌上搜索了一整个上午后找不到解决方案。不确定是否可以使用 AngularJS 更新本地 json 文件。任何帮助,将不胜感激。
Here is my code.
这是我的代码。
getData: function(datatype){
var url = "data/" + datatype + ".json";
return $resource(url, {}, {
query: {
method: "GET",
isArray: true
}
});
},
Call the getData() function in another service function:
在另一个服务函数中调用 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:
作业.json:
[
{
"id": 554114,
"name": "names and numbers",
"facility_id": 0
},
...
]
采纳答案by Chris
This Stackoverflow question and answer might be of some use to you: Edit a file using javascript
这个 Stackoverflow 问题和答案可能对你有用:Edit a file using javascript
In short; Javascript typically can't write to a file unless you're making a post back to a server which can then do the update to your json file.
简而言之; Javascript 通常无法写入文件,除非您向服务器发回消息,然后服务器可以对 json 文件进行更新。
Hope this helps.
希望这可以帮助。
回答by MoGun
The answer above by Chris doesn't seem to be on point. The original question is about Save using angular's $resource. Not whether javascript can write to file.
上面 Chris 的答案似乎并不正确。最初的问题是关于使用 angular 的 $resource 保存。不是javascript是否可以写入文件。
$resource has "Post" defined already on it. So a $resource.save() called correctly will make the post back call to the server. On the server you still need to write code to preserve the posted data. But the bottom line is $resource allows Post.
$resource 上已经定义了“Post”。因此,正确调用 $resource.save() 将使回传调用服务器。在服务器上,您仍然需要编写代码来保存发布的数据。但底线是 $resource 允许发布。
shaosh seem to have issues with the $resource.save
shaosh 似乎对 $resource.save 有问题
回答by MoGun
postis your resource. Not post(i)
帖子是你的资源。不发布(i)
So don't you have to do a
所以你不必做一个
post.$save();
instead of post[i].$save() ?
而不是 post[i].$save() ?