0

I'm trying to share data between 2 controllers that are on 2 different pages, but it's not working as expected.

page1.html:

<form ng-controller="FormController">
<input ng-model="user.email">
</form>

page1controller.js:

 app.controller("FormController", ['$scope', '$http', '$window', 'UserEmailService', function($scope, $http, $window, UserEmailService) {
  // Code logic here
  console.log($scope.user.email) // Code outputs a string here
  UserEmailService.setEmail($scope.user.email);
  $window.location.href = "/page2"; // Redirects to page2.html after logic completes
}]);

page2.html:

<div controller="SomeController">
<p> Hi, your e-mail is {{ email }} </p>
</div>

SomeController.js:

  app.controller("SomeController", ['$scope', 'UserEmailService', function($scope, UserEmailService) {
    console.log(UserEmailService.getEmail()); // outputs undefined
    $scope.email = UserEmailService.getEmail();
  }]);

UserEmailService.js

app.service("UserEmailService", function(){
    var email = [];

    var setEmail = function(val) {
      email.push(val);
    };

    var getEmail = function() {
      return email.pop();
    };

    return {
      setEmail : setEmail,
      getEmail : getEmail
    };


  });

I'm trying to get the user e-mail from page1.html and displaying it on page2.html, but it always comes up as undefined on page2.html. What am I doing wrong?

freetoplay
  • 657
  • 2
  • 8
  • 23

2 Answers2

1

In FormController, $window.location.href will cause a full page reload, which make your service state reset. Try $location.url('') to navigate to that route. It does not cause a full page reload.

If you want your data available after a full page reload. You should use something like localstorage instead.


Use factory instead of service. For more information angular.service vs angular.factory

app.factory("UserEmailService", function(){
  var email = [];

  var setEmail = function(val) {
    email.push(val);
  };

  var getEmail = function() {
    return email.pop();
  };

  return {
    setEmail : setEmail,
    getEmail : getEmail
  };

});
Community
  • 1
  • 1
Rodson
  • 566
  • 4
  • 10
0

In your listening controller (SomeController)

$scope.$watch(function () { 
    return UserEmailService.getEmail();
},
function (newValue, oldValue) {
    if (newValue !== oldValue){
        $scope.user.email = newValue;
    }
});

So that your final code looks like

    app.controller("SomeController", ['$scope', 'UserEmailService', function($scope, UserEmailService) {
        $scope.$watch(function () { return UserEmailService.getEmail();},
            function (newValue, oldValue) {
                if (newValue !== oldValue){
                    $scope.user.email = newValue;
                }
        });
    }]);
AdityaParab
  • 7,024
  • 3
  • 27
  • 40