When calling $save on an ngResource, is it possible to POST only the edited fields rather than POSTing the entire model each time?
var User = $resource('http://example.com/user/123/');
User.get(function(user) {
user.name="John Smith";
user.$save();
// What I *want* -> POST: /user/123/ {name:'John Smith'}
// What currently happens -> POST: /user/123/ {name:'John Smith', age: 72, location: 'New York', noOfChildren: 5}
});
When I want to save only one field, I use the static .save()
method, with a callback that takes the response from that and updates the local object on success:
$scope.saveOneField = function(modelInstance) {
ModelName.save({
id: modelInstance.id,
theField: <some value>
}, function(response) {
// If you want to update *all* the latest fields:
angular.copy(response, modelInstance.data);
// If you want to update just the one:
modelInstance.theField = response.data.theField;
});
};
This assumes that when a POST request is sent to the resource (ie, /modelnames/:id
), your server responds with the latest updated version of the modelInstace.
No, it's not possible, at least not on instances, see http://docs.angularjs.org/api/ngResource.$resource
[...] The action methods on the class object or instance object can be invoked with the following parameters:
- HTTP GET "class" actions:
Resource.action([parameters], [success], [error])
- non-GET "class" actions:
Resource.action([parameters], postData, [success], [error])
- non-GET instance actions:
instance.$action([parameters], [success], [error])
So, it's only possible by passing the data to save to the "static" save method, ie User.save
. Something like this:
User.get(function(user)
{
user.name = 'John Smith';
User.save({name: user.name});
});
Whether this works out for you will probably depend on what you're going to do with the user
instance.