最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scope variable not accessible (undefined) - AngularJS - Stack Overflow

programmeradmin0浏览0评论

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?

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 asked Apr 14, 2014 at 14:56 FootsieNGFootsieNG 8193 gold badges12 silver badges27 bronze badges 1
  • 1 Possible duplicate : How can I pass variables between controllers in AngularJS? – YAAK Commented Apr 14, 2014 at 15:11
Add a ment  | 

3 Answers 3

Reset to default 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);               

});

$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

发布评论

评论列表(0)

  1. 暂无评论