title: AngularJS Service Passing Data Between Controllers
body: <p>When using an AngularJS service to try and pass data between two controllers, my second controller always receives undefined when trying to access data from the service. I am guessing this is because the first service does a $window.location.href and I'm thinking this is clearing out the data in the service? Is there a way for me to change the URL to a new location and keep the data persisted in the service for the second controller? When I run the code below the alert in the second controller is always undefined.</p>
  
  <p><strong>app.js (Where Service is Defined)</strong></p>
  
  <pre><code>var app = angular.module('SetTrackerApp', ['$strap.directives', 'ngCookies']);
  
  app.config(function ($routeProvider) 
  {
  $routeProvider
    .when('/app', {templateUrl: 'partials/addset.html', controller:'SetController'})
    .when('/profile', {templateUrl: 'partials/profile.html', controller:'ProfileController'})
    .otherwise({templateUrl: '/partials/addset.html', controller:'SetController'});
  });
  
  app.factory('userService', function() {
  var userData = [
      {yearSetCount: 0}
  ];
  
  return {
      user:function() {
          return userData;
      },
      setEmail: function(email) {
          userData.email = email;
      },
      getEmail: function() {
          return userData.email;
      },
      setSetCount: function(setCount) {
          userData.yearSetCount = setCount;
      },
      getSetCount: function() {
          return userData.yearSetCount;
      }
  };
  });
  </code></pre>
  
  <p><strong>logincontroller.js: (Controller 1 which sets value in service)</strong></p>
  
  <pre><code>    app.controller('LoginController', function ($scope, $http, $window, userService) {
  
  $scope.login = function() {
      $http({
          method : 'POST',
          url : '/login',
          data : $scope.user
      }).success(function (data) {
          userService.setEmail("foobar");
          $window.location.href = '/app'
      }).error(function(data) {
          $scope.login.error = true;
          $scope.error = data;
      });
  }
  });
  </code></pre>
  
  <p><strong>appcontroller.js (Second controller trying to read value from service)</strong></p>
  
  <pre><code>app.controller('AppController', function($scope, $http, userService) {
  
  $scope.init = function() {      
      alert("In init userId: " userService.getEmail());
  }
  
  });
  </code></pre>