I found that I was writing a lot of boilerplate code and repeating myself making a new factory for each model I wanted to access. It was also bloating the dependencies on my controllers.
Here I describe how to create an API service that covers all of your data factories
myApp.factory('Api', ['$resource',
function($resource) {
return {
Posts: $resource('/posts/:id', {id: '@id'}),
Users: $resource('/users/:id', {id: '@id'}),
Categories: $resource('/categories/:id', {id: '@id'})
};
}]);
Now you can use it in your controllers like so:
myApp.controller("myCtrl", function($scope, Api){
$scope.user = Api.Users.get({id: 1});
$scope.posts = Api.Posts.query();
}
Related External Links: