简体   繁体   中英

Scope variable not accessible (undefined) - AngularJS

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?

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

});

$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:

AngularJS Service Passing Data Between Controllers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM