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

时间:2015-09-21 02:46:56

标签: javascript angularjs

我正在尝试在2个不同页面上的2个控制器之间共享数据,但它没有按预期工作。

page1.html:

[{"name"=>"xxx", "price"=> xxx},{}......]

page1controller.js:

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

page2.html:

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

SomeController.js:

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

UserEmailService.js

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

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

2 个答案:

答案 0 :(得分:1)

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

如果您希望在整页重新加载后提供数据。你应该使用像localstorage这样的东西。

使用工厂代替服务。有关详细信息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
  };

});

答案 1 :(得分:0)

在你的听力控制器(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;
                }
        });
    }]);
相关问题