Scope variable not accessible (undefined) - AngularJS
Question
I am setting a scope variable in one controller, then changing location to another view. Then in the controller of the new view the scope variable is no longer accessible, it states it is 'undefined'. I have added a simplified version of the problem below and would appreciate any help.
app.controller('loginController', function ($scope,$location){
$scope.loginUser = function (user) {
$scope.userId = "USERID";
$location.path('/view3');
}
});
Controller for view 3
app.controller('videoListController', function($scope){
alert("UserID: "+$scope.userId);
});
The value of $scope.userId
appears as 'undefined
'. What am I doing wrong?
Solution
You can also use $rootScope
for global access in AngularJS
Take a look at this
app.controller('loginController', function ($scope,$rootScope,$location){
$scope.loginUser = function (user) {
$rootScope.userId = "USERID";
$location.path('/view3');
}
});
app.controller('videoListController', function($scope, $rootScope){
alert("UserID: "+$rootScope.userId);
});
OTHER TIPS
$scope
isn't shared between controllers. If you need to pass data between controllers, it needs to be stored somewhere else that is persistent.
Scope is defined per controller... You still have the option to use $scope.$parent
or $rootScope
to link controllers but I would use those carefully.
Angular Services are based on singleton patterns. You can also use those to share information between controllers and I think it will be the best approach.
I found that this has been previously discussed and here are some good examples: