13

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

4

1 回答 1

9

这应该可以正常工作:

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

我猜你在它之前正在读取它。

更新

这里的调试体验真的很奇怪。但是,在我更新的 plunker 中,您可以通过读取后发生写入的时间戳看到:

http://plnkr.co/edit/pn5Wxk

于 2013-08-21T13:29:08.253 回答