[英]Does $scope inherit properties from $rootScope? AngularJS
我有Angular(v1.2.8)應用程序,其中文件如下所示:
Index.html
<div> Menu </div>
<div ng-view ></div>
<div> Footer </div>
PartialView.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;
}
...
});
我想為每個登錄用戶(Joe,Dave)加載特定的配置。 但是我的問題是,當我與另一個用戶(Dave)登錄時,我將獲得以前登錄的用戶(Joe)的配置。
我不明白,因為當我注銷時,執行銷毀回調,其中$scope.userConfig = null;
叫做
在有一個新用戶登錄(Dave)的情況下,我希望$scope.userConfig
為null,因此可以運行$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事件,它只是分配空的userConfig
對對象$scope
,而不是在$rootScope
本身。
下次進入控制器時,查找$scope.userConfig
,實際上在該$scope
上$scope
null,但是它上升並在$rootScope
上找到它,這就是為什么要輸入if
語句的原因,因此需要從$rootScope
中將其刪除,並在銷毀時將其刪除。
再考慮一下在這兩個范圍內是否都需要它,我想$rootScope
就足夠了。
從控制器文檔中 :
每個Controller收到的$ scope將有權訪問層次結構中更高級別的Controller定義的屬性和方法。
因此,當您要求!$scope.userConfig
從$scope.$parent
獲取它時,它可以是$ rootscope,也可以不是$ rootscope,這取決於您使用該控制器定位元素的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.