2013-07-30 166 views
20

当使用AngularJS服务尝试在两个控制器之间传递数据时,当尝试访问服务中的数据时,我的第二个控制器总是收到未定义的值。我猜这是因为第一个服务执行$ window.location.href,我认为这将清除服务中的数据?有没有一种方法可以让我将URL更改为新位置,并将数据保留在第二个控制器的服务中?当我在第二个控制器中的警报下面运行代码时,总是未定义。AngularJS服务在控制器之间传递数据

app.js(其中服务被定义)

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

logincontroller.js:(控制器1它设置在服务值)

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

appcontroller.js(第二控制器试图从服务中读取数值)

app.controller('AppController', function($scope, $http, userService) { 

$scope.init = function() {  
    alert("In init userId: " userService.getEmail()); 
} 

}); 

回答

27

这样定义

app.service('userService', function() { 
    this.userData = {yearSetCount: 0}; 

    this.user = function() { 
     return this.userData; 
    }; 

    this.setEmail = function(email) { 
     this.userData.email = email; 
    }; 

    this.getEmail = function() { 
     return this.userData.email; 
    }; 

    this.setSetCount = function(setCount) { 
     this.userData.yearSetCount = setCount; 
    }; 

    this.getSetCount = function() { 
     return this.userData.yearSetCount; 
    }; 
}); 

退房邓肯的答案在这里为您服务:

AngularJS - what are the major differences in the different ways to declare a service in angular?

+0

感谢@乔希 - Petitt。我仍然未定义,但我现在认为这是因为在第二页我转换这是一个完整的HTML文档,我在HTML元素中有一个ng-app指令。所以我猜这就是清除服务数据的原因?这听起来正确吗? – AquaLunger

+0

也许,很难说,没有看整个应用程序。 FWIW,这是我一直在努力学习的AngularJS项目。你可能会在应用程序/用户目录周围徘徊,看看我是如何实现它的。我可以在不同的页面上使用userService。 https://github.com/jpmec/done –

+0

@ user1093077嗨,你有没有得到你的解决方案的工作。我有同样的问题:http://stackoverflow.com/questions/20118335/angular-dependency-injection-passing-values-between-modules-using-service –

相关问题