AngularJS $rootScope variable exists, but not accessible

廉价感情. 提交于 2019-11-29 13:01:13

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";
})

`

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
    }]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!