I think this seems like an obvious question, but my brain seems to be a bit fried.
I have a resource
Book = $resource("/books/:id", {id: "@id"});
book = Book.get(1);
I want to refresh the object to get changes from the server.
I know I can do that by repeating book = Book.get(book.id)
, but that would mean that everything on the page that's watching book
would temporarily get nulled until the query returned and functions that operate on it might crash.
I want to add a reload method to instances that updates any changed fields once the query returns from the server. My best attempt so far is:
$reload = function() {
var model = this;
Book.get(model.id, function(data) { // success
angular.forEach(data, function(value, key) {
model[key] = value;
}
}
}
Two questions a) Is this the "angular" way to do it, or is there a more elegant way? a) How do I add this $refresh method when defining the resource so that it gets included on every instance created?
Try to extent it's prototype:
var Book = $resource("/books/:id", {id: "@id"});
Book.prototype.reload = function(callback) {
return this.get(this.id, callback);
}
var book = Book.get(1);
book.reload(function(data){console.log(data);});
thanks to: @mathew-berg (Mathew Berg) for making fixes on my code.