In Backbone.js
, one can instantiate a model with pre-existing JSON data by using
var user = new Backbone.Model({ name: "John Doe", age: 30 });
And then perform updates with a single call
user.save({ age: 31 }, { success: successCallback, error: errorCallback });
This comes handy in all sorts of scenarios, such as when that data is already available on the client through caching or pre-populated templates (like using <%= raw @user.to_json %>
in rails erb templates).
I'm curious to know how this is done when using $resource
with Angular.js
. Right now, I have a situation where my data is cached on the client before the $resource
is created, and I'd like to update it without making an extra GET
call to populate the object:
app.factory('User', ['$resource', function($resource) {
return $resource('/users/:user_id.json', { user_id: '@id' }, {
get: { method: 'GET' },
save: { method: 'PUT' },
create: { method: 'POST' },
destroy: { method: 'DELETE' }
});
}]);
And somewhere in my controller I'd like to just update an existing user without fetching it from the server:
app.controller('UsersController', ['User', function(User) {
// somehow initialize a user from an existing
// object, say { name: "John Doe", age: 30 }
user.age = 31
user.$save()
// instead of doing this
User.get({ user_id: 100 }, function(user, respHeaders) {
user.age = 31
user.$save()
});
}]);
I'm probably still in the Backbone mindset, but I'm really curious if I'm approaching this all wrong. Thanks.
$resource gives the option to create a new user like you would with any object:
var user = new User({name : 'John Doe', age: 30});
user.age = 32;
user.$save();
Resource Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With