I am trying to access a global variable via a normal function, is it possible?
I have set some var using $rootScope and I am trying to access this via a callback function.
This callback is called from controller. I don't want to pass $rootScope
in that callback.
Is there any way to access that $rootScope.var
?
I am open to use service if it is possible.
Please suggest.
Thanks
I am trying to access rootScope as following:
function fbLandingCtrl($scope, $rootScope) {
$rootScope.isFBLoggedin = false;
$scope.login = function() {
console.log( $rootScope.isFBLoggedin);
fbHelper.login(getUserInfo);
};
function getUserInfo(){
fbHelper.getUserInfo(updateStatus);
}
function updateStatus(userInfo){
$rootScope.isFBLoggedin = true;
console.log( $rootScope.isFBLoggedin);
}
}
and my service is as:
myapp.factory('FBService', [ '$rootScope', function ($rootScope) {
$rootScope.isFBLoggedin = false; // global variable
$rootScope.userName = null;
$rootScope.userEmail = null;
return {
getStatus: function() {
return $rootScope.isFBLoggedin;
},
setStatus: function(status) {
console.log("Status:"+status);
return $rootScope.isFBLoggedin = status;
}
};
}]);
it is showing isFBLoggedin as true under updateStatus fn but it is not reflecting on view
I am printing {{isFBLoggedin}}
but is ts showing false
Finally Its working.
I followed @dluz's solution.
I also used $rootScope.$apply(function() {}})
to render views
Please don't use the $rootScope to define any function - it's really bad practice. Remember that $rootScope is a global variable after all.
You can get the $rootScope via service like this:
$rootScope exists, but it can be used for evil
UPDATED ANSWER
A_J, I am not sure what's the scenario of your application. I would need to see more code to give you a better answer, but please take a look at the code below. Maybe it can give you some idea how you can design your code to access
$rootScope
inside aservice
.Press the button "Log me In" and take a look at your console. Working example here (http://jsbin.com/olOyaHa/1/)
You can access $rootScope.var inside your controller if you added $rootScope as a controller reference:
It will work as long as your callback is defined inside your controller.
EDIT: after our discussion, here is how to define a function inside your rootScope: