I am writing my first AngularJs app. The app needs to know the current user in different controllers. The current user is retrieved through a rest call. First i just added current user information on top of the page using $scope:
var currentUser = {};
app.controller('currentUserCtrl', function($scope, $http) {
$scope.currentUser = null;
$http.get(rootUrl + '/timetracker/user/current').success(
function(response) {
$scope.currentUser = response;
currentUser = response;
});
}
);
The controller works fine but "currentUser" can't be accessed by other controllers. My 2nd try (after reading about global variables) was to use $rootScope. So i changed the above $rootScope.currentUser = response;
and omitted the var currentUser
. I added $rootScope
to all my controllers an tried to get currentUser.id
. But this didn't work neither - the user object is null. My third try was to use a factory:
app.factory('currentUser', function($http){
var currentUser = {};
$http.get(rootUrl + '/timetracker/user/current').success(
function(response) {
currentUser = response;
});
return currentUser;
});
My controllers now inject "currentUser" but this is also null (all values i want to get are "undefined"). So how to make current user globally available?
Could it be that the currentUser is used before the async call and write of variable is successful? How to be sure that currentUser call is finished?
EDIT controller that uses currentUser:
app.controller('createBookingCtrl', function($scope, $http, $filter, currentUser) {
//list of projects for current user (usersprojects)
$scope.projectsList = {};
$http.get(rootUrl + '/timetracker/usersprojects/user/' + currentUser.id).success(function(response) {
for (var i = 0; i < response.length; ++i)
//map users project by projects name
$scope.projectsList[response[i].project.name] = response[i];
});
});
currentUser.id
has value undefined.
2nd EDIT
I just tested with js debugger: the in factory currentUser = response
runs after the other controller access to the value. So how to be sure/ wait for response?