0

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
}
2
  • Are the modules on separate parts of the dom? Commented May 22, 2014 at 18:22
  • Put this in a plunkr or something. Impossible to help without an example implementation. Commented May 22, 2014 at 18:28

2 Answers 2

2

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

`

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.