$ scope是否从$ rootScope继承属性? AngularJS

时间:2015-07-29 09:12:01

标签: javascript 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)的配置。

我没有得到它,因为当我退出时,会执行destroy回调,其中调用$scope.userConfig = null;

新用户登录后(Dave),我希望$scope.userConfig为空,因此运行$scope.userConfig = ConfigService.getCurrentUserConfig();

但是,$scope.userConfig包含以前登录用户(Joe)的配置,并且未检索到新配置。

当我突然删除$rootScope.userConfig = $scope.userConfig;时,它开始按照要求进行工作,为什么?

我想将当前用户配置保存到$rootScope,以便我可以在其他控制器中检索它。

2 个答案:

答案 0 :(得分:3)

当要求if (!$scope.userConfig)时,会发生以下情况:

  1. 查看控制器的$ scope以查看它是否具有userConfig对象。 (第一次,它目前没有,所以您将配置放在$scope上,也放在$rootScope上。

  2. 如果在$scope上找不到它,它会在$scope链上升,直到$rootScope来查找。

  3. 当您对目标事件执行:$scope.userConfig = null;时,它只会为 userConfig上的$scope对象指定null,而不是{{1}本身。

    下次当您进入控制器并查找$rootScope时,它$scope.userConfig实际上是空的,但它会上升并在$scope上找到它,这就是为什么您输入$rootScope语句,因此您需要将其从if中删除,以及销毁。

    同时考虑一下这两个范围是否需要它,我认为$rootScope就足够了。

答案 1 :(得分:1)

来自controller documentation

  

每个Controller收到的$ scope可以访问   控制器定义的属性和方法位于层次结构的上方。

所以当你要求!$scope.userConfig$scope.$parent获取它时,它可以是$ rootscope,取决于你使用该控制器找到元素的位置。