title: AngularJS Factory Variable Becomes Undefined
body: <p>I have a user variable within a factory which keeps becoming undefined after switching controllers.  I'm setting the variable in one controller.  When I log user it appears with the data I'm expecting, but when I switch controllers and retrieve the variable it's undefined once again.  Here is the code:</p>
  
  <pre><code>discussionBoard.factory('userFactory', function($http){
  
      console.log("I'm loading the userFactory");
  
      var user = {};
  
      var factory = {};
  
      factory.createUser = function(user, callback){
          $http.post('/users/new', {user: user})
              .success(function(response){
                  user = response[0];
                  callback(user);
              })
      }
  
      factory.retrieveUser = function(callback){
          callback(user);
      }
  
      console.log(user);
  
      return factory;
  
  });
  
  discussionBoard.controller('dashCtrl', function($scope, topicFactory, userFactory){
  
      $scope.createTopic = function(){
          topicFactory.createTopic(function(topic){
              $scope.topic = topic;
          })
      }
  
      userFactory.retrieveUser(function(user){
          $scope.user = user;
      });
  
  });
  </code></pre>
  
  <p>EDIT: After a bit more experimenting I was able to get this to work by adding user as an object within the factory object.  This actually raises another question, however, about how the factory is interacting with AJAX here, as it seems .success() doesn't have access to the factory's scope.  Here's the code that worked, but I'd be curious if anyone could say why this is arranged in this way:</p>
  
  <pre><code>discussionBoard.factory('userFactory', function($http){
  
      var factory = {};
  
      factory.createUser = function(user, callback){
          $http.post('/users/new', {user: user})
              .success(function(response){
                  factory.user = response[0];
                  callback(factory.user);
              })
      }
  
      factory.user = {};
  
      factory.retrieveUser = function(callback){
          callback(factory.user);
      }
  
      return factory;
  
  });
  
  discussionBoard.controller('dashCtrl', function($scope, topicFactory, userFactory){
  
      $scope.createTopic = function(){
          topicFactory.createTopic(function(topic){
              $scope.topic = topic;
          })
      }
  
      userFactory.retrieveUser(function(user){
          $scope.user = user;
      });
  
  });
  </code></pre>