AngularJS $rootScope variable exists, but not accessible

前端 未结 2 1133
囚心锁ツ
囚心锁ツ 2020-12-20 10:07

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

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 10:40

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

提交回复
热议问题