[英]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视图 3 的控制器
app.controller('videoListController', function($scope){
alert("UserID: "+$scope.userId);
});
The value of $scope.userId
appears as 'undefined
'. $scope.userId
的值显示为'undefined
”。 What am I doing wrong?我究竟做错了什么?
You can also use $rootScope
for global access in AngularJS您还可以在 AngularJS 中使用
$rootScope
进行全局访问
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. $scope
不在控制器之间共享。 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.范围是按控制器定义的...您仍然可以选择使用
$scope.$parent
或$rootScope
来链接控制器,但我会谨慎使用它们。
Angular Services are based on singleton patterns. Angular 服务基于单例模式。 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 AngularJS 服务在控制器之间传递数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.