2013-07-30 82 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 –

相關問題