Angularjs $rootscope Variable Exists, But Not Accessible
Solution 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";
})
`
Solution 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
}]);
Post a Comment for "Angularjs $rootscope Variable Exists, But Not Accessible"