Skip to content

Instantly share code, notes, and snippets.

@fiznool
Created April 17, 2014 14:27
Show Gist options
  • Save fiznool/10987626 to your computer and use it in GitHub Desktop.
Save fiznool/10987626 to your computer and use it in GitHub Desktop.
Patch for angularjs $resource to send POST or PUT depending on ID field
// This patches the $resource.$save function
// to make a PUT when an ID is present.
// Inspired by http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/
'use strict';
angular.module( 'fz.restsource', [ 'ngResource' ] )
.factory('$restsource', function($resource) {
var idField = '_id';
return function( url, params, methods ) {
var defaults = {
update: { method: 'put', isArray: false },
create: { method: 'post' }
};
methods = angular.extend(defaults, methods);
var resource = $resource(url, params, methods);
resource.prototype.$save = function() {
if (!this[idField] ) {
return this.$create.apply(this, arguments);
} else {
return this.$update.apply(this, arguments);
}
};
return resource;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment