title: Using factory to expose a simple API
body: <p>I'm trying to write a factory which exposes a simple users API. I'm new to AngularJS and I'm a bit confused about factories and how to use them. I've seen other topics but none that are a good match to my use case.</p>
  
  <p>For the sake of simplicity, the only functionality I'd like to achieve is getting all users in an array and then pass them to a controller through the injected factory.</p>
  
  <p>I stored the users in a json file (for now I only want to read that file, without modifying the data)</p>
  
  <p><strong>users.json:</strong></p>
  
  <pre><code>[
  {
      "id": 1,
      "name": "user1",
      "email": "a@b.c"
  },
  {
      "id": 2,
      "name": "user2",
      "email": "b@b.c"
  }
  ]
  </code></pre>
  
  <p>The factory I'm trying to write should be something like this: </p>
  
  <p><strong>UsersFactory:</strong></p>
  
  <pre><code>app.factory('usersFactory', ['$http', function ($http) {
      return {
          getAllUsers: function() {
              return $http.get('users.json').then(
                  function(result) {
                      return result.data;
                  },
                  function(error) {
                      console.log(error);
                  }
              );
          }
      };
  }]);
  </code></pre>
  
  <p>And finally, the controller call would be like this:</p>
  
  <p><strong>UsersController</strong></p>
  
  <pre><code>app.controller('UsersCtrl', ['$scope', 'usersFactory', function($scope, usersFactory){
      usersFactory.getAllUsers().then(function (result) {
          $scope.users = result;
      });
  }]);
  </code></pre>
  
  <p>I've searched the web and it seems like it is not really a good practice to use factories this way, and if I'd like to achieve some more functionality like adding/removing a new user to/from the data source, or somehow store the array within the factory, that wouldn't be the way to do it. I've seen some places where the use of the factory is something like <code>new UsersFactory()</code>.</p>
  
  <p>What would be the correct way to use factories when trying to consume APIs?</p>
  
  <p>Is it possible to initialize the factory with an object containing the <code>$http.get()</code> result and then use it from the controller this way?</p>
  
  <pre><code>var usersFactory = new UsersFactory(); // at this point the factory should already contain the data consumed by the API
  usersFactory.someMoreFunctionality();   
  </code></pre>