Here is how I did it. Thus, you do not need to write a custom resource function for each of your endpoints, you simply add it to the list of resources in the list. I defined a list of endpoints that I wanted to use as follows.
var constants = { "serverAddress": "foobar.com/", "resources": { "Foo": { "endpoint": "foo" }, "Bar": { "endpoint": "bar" } } }
Then resources are created from each of them, like this.
var service = angular.module('app.services', ['ngResource']); var resourceObjects = constants.resources; for (var resourceName in resourceObjects) { if (resourceObjects.hasOwnProperty(resourceName)) { addResourceFactoryToService(service, resourceName, resourceObjects[resourceName].endpoint); } } function addResourceFactoryToService (service, resourceName, resourceEndpoint) { service.factory(resourceName, function($resource) { return $resource( constants.serverAddress + resourceEndpoint + '/:id', { id: '@id', }, { update: { method: 'PUT', params: {id: '@id'} }, } ); });
}
The best part is that it takes 2 seconds to add a new endpoint, and I even chose the put method for you. You can then embed any of your resources in your controllers like this.
.controller('homeCtrl', function($scope, Foo, Bar) { $scope.foo = Foo.query(); $scope.bar = Bar.get({id:4}); }
source share