Angular服务在新控制器中丢失设置数据

时间:2016-09-29 20:39:51

标签: angularjs

我有一个链接,我想用它来将数据传递到另一个页面。我能够访问我去的页面上的服务,但数据是空的。

HTML:

<a href="/signup" ng-click="saveSubscriptionData()"">Female</a>

服务:

var app = angular.module('boxHome', []);

app.controller('boxHomeController', function ($scope, SubscriptionService) {
    $scope.saveSubscriptionData = function() {
        SubscriptionService.gender = 'male';
        SubscriptionService.subscription = 'infant';
        console.log(SubscriptionService);
    }
});

app.factory('SubscriptionService', function () {
    return {
        gender: '',
        subscription: ''
    };
});

上述日志语句返回性别:'男性'和订阅:'婴儿'。

我链接到的页面:

var appSignup = angular.module('boxSignup', ['boxHome']);

appSignup.controller('boxSignupController', function ($scope, SubscriptionService) {
    $scope.init = function (domainId) {
        console.log(SubscriptionService);
    };
});

我希望上面的日志语句返回性别:'男性'和订阅:'婴儿'。它返回性别:''和订阅''。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

app.service('SubscriptionService',function(){
   var gender='';
   var subscription='';
   this.save=function(gender,subscription){        
      this.gender=gender;
      this.subscription=subscription;
   };

   this.getGender=function(){
      return gender; 
   };

   this.getSubscription=function(){
      return subscription;
   };
}); 


.controller('boxHomeController', function ($scope, SubscriptionService) {
    $scope.saveSubscriptionData = function() {
        SubscriptionService.save('male','infant');
    }
 });

答案 1 :(得分:0)

每次调用工厂都会返回JSON对象的新实例,因此不会共享状态。要解决此问题,请在工厂内声明一个返回的对象:

app.factory('SubscriptionService', function () {
    var service = {};

    var info = {};
    info.gender = '';
    info.subscription = '';

    service.getInfo = getInfo;

    function getInfo(){
        return info;
    }

    return service;
});

使用时:

var info = SubscriptionService.getInfo();
console.log(info.subscription);