shaosh
shaosh

Reputation: 687

How to update data in a json file in AngularJS?

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.

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:

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
},
...
]

Upvotes: 2

Views: 19203

Answers (3)

MoGun
MoGun

Reputation: 104

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.

$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.

shaosh seem to have issues with the $resource.save

Upvotes: 5

Chris
Chris

Reputation: 6325

This Stackoverflow question and answer might be of some use to you: 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.

Hope this helps.

Upvotes: 0

MoGun
MoGun

Reputation: 104

post is your resource. Not post(i)

So don't you have to do a

      post.$save(); 

instead of post[i].$save() ?

Upvotes: 1

Related Questions