Last active
December 20, 2015 04:19
-
-
Save dsferruzza/6069617 to your computer and use it in GitHub Desktop.
AngularJS: resources that handle PUT call for modifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired from: http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/ | |
var resource = angular.module('Resource', ['ngResource']); | |
resource.factory('Resource', ['$resource', function($resource) { | |
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(success, error) { | |
if (!this.id) { | |
return this.$create(success, error); | |
} | |
else { | |
return this.$update(success, error); | |
} | |
}; | |
return resource; | |
}; | |
}]); | |
// HOW TO USE | |
var services = angular.module('services', ['Resource']); | |
services.factory('User', ['Resource', function($resource) { | |
return $resource('/api/user/:id', {id: '@id'}); | |
}]); | |
// In controllers: it works the same way as ngResource |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment