My brain feels a bit fried today, so pardon what might seem like an obvious question.
I have a useful resource at my disposal:
Book = $resource("/books/:id", {id: "@id"});
book = Book.get(1);
When I want to refresh the object to receive any updates from the server, I know I can simply repeat book = Book.get(book.id)
. However, doing so would cause everything on the page that relies on book
to temporarily become null until the query returns, potentially causing functions operating on it to crash.
My goal is to create a reload method for instances that automatically updates changed fields once the query results return. Here's my best attempt so far:
$reload = function() {
var model = this;
Book.get(model.id, function(data) { // success
angular.forEach(data, function(value, key) {
model[key] = value;
}
}
}
I have two questions: a) Is this considered the "angular" way to achieve this, or is there a more elegant approach? b) How can I incorporate this $refresh method when defining the resource so that it is included in every instance created?