Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
1  
Possible duplicate : How can I pass variables between controllers in AngularJS? –  YAAK Apr 14 at 15:11
add comment

3 Answers

up vote 2 down vote accepted

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

});
share|improve this answer
add comment

$scope isn't shared between controllers. If you need to pass data between controllers, it needs to be stored somewhere else that is persistent.

share|improve this answer
    
Oh ok. What would you say is the best way to pass variables between controllers then? –  FootsieNG Apr 14 at 15:00
add comment

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:

AngularJS Service Passing Data Between Controllers

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.