>我有 Angular (v1.2.8( 应用程序,其中文件如下所示:
索引.html
<div> Menu </div>
<div ng-view ></div>
<div> Footer </div>
部分视图.html
<div ng-controller='ItemsController'> ... </div>
应用配置
itemsApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/items', {
templateUrl: 'views/items/PartialView.html',
controller: 'ItemsController'
});
$routeProvider.when('/login', {
templateUrl: 'views/authentication/login.html',
controller: 'LoginController'
});
$routeProvider.when('/logout', {
templateUrl: 'views/authentication/logout.html',
controller: 'LoginController'
});
...
控制器
itemsApp.controller('ItemsController', function($scope, $rootScope, ConfigService) {
...
if (!$scope.userConfig) {
$scope.userConfig = ConfigService.getCurrentUserConfig();
$rootScope.userConfig = $scope.userConfig;
}
$scope.$on('$destroy', function () {
$scope.userConfig = null;
}
...
});
我想为每个登录用户(乔、戴夫(加载特定配置。但我的问题是,当我使用其他用户(Dave(登录时,我将获得以前登录的用户(Joe(的配置。
我不明白,因为当我注销时,会执行销毁回调,其中调用$scope.userConfig = null;
登录新用户 (Dave( 后,我希望$scope.userConfig
为空,因此运行$scope.userConfig = ConfigService.getCurrentUserConfig();
.
但相反,$scope.userConfig
包含以前登录的用户 (Joe( 的配置,并且不会检索新配置。
当我删除$rootScope.userConfig = $scope.userConfig;
时,它突然开始按预期工作,为什么?
我想将当前用户配置保存到 $rootScope
中,以便我可以在其他控制器中检索它。
请求if (!$scope.userConfig)
时,会发生以下情况:
-
查看控制器的$scope以查看它是否具有
userConfig
对象。(第一次,它目前没有它,所以你把你的配置放在$scope
上,也放在$rootScope
上(。 -
当在
$scope
上找不到它时,它会沿着$scope
链向上,直到$rootScope
寻找它。
当你这样做时:$scope.userConfig = null;
你的 destory 事件,它只是将 null 分配给该$scope
上的userConfig
对象,而不是$rootScope
本身。
下次当您进入控制器并查找 $scope.userConfig
时,它实际上是在该$scope
上为 null ,但它上升并在$rootScope
上找到它,这就是您输入 if
语句的原因,因此您需要在销毁时将其从$rootScope
中删除。
还要考虑一下您是否在这两个作用域上都需要它,我想$rootScope
就足够了。
来自控制器文档:
每个控制器接收的$scope将有权访问 由层次结构上级控制器定义的属性和方法。
因此,当您要求!$scope.userConfig
时,它会从 $scope.$parent
,这可以是$rootscope的,也可以不是,具体取决于您使用该控制器定位元素的位置。