Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - $rootScope property value undefined in service

I am currently creating a new property in $rootScope and setting its value in one module.

$rootScope.test = 123;

I am then trying to reference this value later in a service function.

.factory("testFactory", function ($location, $http, $rootScope) {
    /* .... */
    return {
        testFunction : function(){
            console.log($rootScope);
            console.log($rootScope.test);
        },
        /* .... */

When I view the console output in Chrome, I can see that the value of test is being set properly in the $rootScope object, but I am unable to reference using the $rootScope.test syntax. $rooScope.test simply returns undefined.

Is there any reason that you can't reference property values of $rootScope in services? Or am I attempting to retrieve this value improperly?


UPDATE - I have created a Plunker that demonstrates the issue that I am running into. http://plnkr.co/edit/ePEiYh

like image 810
ral8 Avatar asked Aug 21 '13 13:08

ral8


1 Answers

This should work just fine:

var myApp = angular.module("myApp", []);

myApp.run(['$rootScope', function($rootScope){
    $rootScope.test = 123;
}]);

myApp.controller('AppController', ['$rootScope', function ($rootScope) {
    console.log($rootScope.test);
}]);

Plunker: http://plnkr.co/edit/7NTGOK

I guess that you are reading the value before you are writing it.

UPDATE

The debugging experience is really weird here. However, in my updated plunker you can see through the timestamps that the writing happens after reading:

http://plnkr.co/edit/pn5Wxk

like image 86
Christoph Avatar answered Sep 30 '22 20:09

Christoph