AngularJS $rootScope variable exists, but not acce

2019-01-27 09:43发布

问题:

I set a $rootScope variable in one of my modules and now want to access that same $rootScope variable in another module. Thus far I can see that in both modules the variable has been set properly, but when I try accessing the variable in $rootScope, I only get undefined.

How can I access this variable without doing a factory/service workaround? The variable is really simple and $rootScope should suffice for what I need. I've put some generic sample code below to illustrate the issue:

file1.js

var app = angular.module('MyApp1', []);

app.controller('Ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
    $scope.myFunc = function() {
        $rootScope.test = 1;
    }
}

file2.js

var app = angular.module('MyApp2', []);

app.controller('Ctrl2', ['$scope', '$rootScope', function($scope, $rootScope) {
    $scope.need_to_access_this = $rootScope.test; // undefined
    console.log($rootScope); // returns JS object w/ test property set to 1
}

回答1:

I was just stuck in the same problem when I figured out that you have define those properties for $rootScope before the controllers or services load. So what I did was set inital values when the application runs. In your case it will be like:

app.run(function($rootScope){
    $rootScope.test="variable";
})

`



回答2:

In Ctrl1 the $rootScope.test value is set inside the $scope.myFunc.

The problem is that you aren't calling that function, so the test property in $rootScope is never set.

You need to call $scope.myFunc(); in Ctrl1 or set $rootScope.test = 1; dirrectly in the Controller:

app.controller('Ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
    $scope.myFunc = function() {
        $rootScope.test = 1;
    };

    $scope.myFunc();
}

or

app.controller('Ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
    $rootScope.test = 1;
}

EDIT:

The above suggestions still remain valid, thus you need to call myFunc().

But the problem with your code is that Ctrl1 belongs to MyApp1 and Ctrl2 belongs to MyApp2.

Every application has a single root scope (docs here)

You will need to create Ctrl2 as a controller of MyApp1:

angular.module('MyApp1')
    .controller('Ctrl2', ['$scope', '$rootScope', function($scope, $rootScope) {
        $scope.need_to_access_this = $rootScope.test; // undefined
        console.log($rootScope); // returns JS object w/ test property set to 1
    }]);