控制器之间的数据共享不能按预期工作

Sharing data among controllers not working as expected

本文关键字:工作 不能按 数据共享 之间 控制器      更新时间:2023-09-26

我试图在2个不同页面上的2个控制器之间共享数据,但它不像预期的那样工作

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
    };

  });

我试图从page1.html中获取用户电子邮件并在page2.html上显示它,但它总是在page2.html上显示为未定义。我做错了什么?

FormController中,$window.location.href将导致整个页面重新加载,从而使您的服务状态重置。尝试$location.url('')导航到该路线。它不会导致整个页面重新加载。

如果您希望您的数据在整个页面重新加载后可用。你应该使用localstorage之类的东西。


使用factory代替service。更多信息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
  };
});

在您的监听控制器(SomeController)

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

最后的代码看起来像

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