Grouping Factories Together To API Service In AngularJS

Posted by Weston Ganger on July 11, 2015

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:

Posted in Angular and Tagged with angularjs factory service api 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts