2

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?

1

3 Answers 3

4

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

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

Comments

2

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

1 Comment

Oh ok. What would you say is the best way to pass variables between controllers then?
1

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

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.