Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

javascript - AngularJS $rootScope variable exists, but not accessible

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...