$scope是否继承$rootScope的属性?AngularJS.
Does $scope inherit properties from $rootScope? AngularJS
>我有 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的,也可以不是,具体取决于您使用该控制器定位元素的位置。
- AngularJS-使用'true'属性
- AngularJS指令出错-无法读取属性'编译'的未定义
- angularjs无法读取未定义的属性then
- AngularJS:如何用同一对象的另一个属性访问一个属性
- 如何在AngularJS工厂中正确声明对象属性
- 无法访问指令中的AngularJS属性
- 使用angularjs内置过滤器过滤代码中的特定属性
- angularjs如何从返回值中找到正确的属性
- 使用AngularJS动态更改css属性
- AngularJS-筛选对象中的选定属性
- Angularjs指令如何检测属性中的更改
- 将信息框作为HTML标签属性(AngularJS)添加到Google Maps Marker
- 如何访问返回的 json 对象的属性?(AngularJS)
- 无法读取未定义(表单验证)的属性 - angularjs
- 访问模板中输入元素的属性 - AngularJS
- 通过模型属性 AngularJS 获取节点元素
- 选择基于属性AngularJS的控制器
- 有条件地应用属性(AngularJS)
- 无法访问对象属性angularjs
- $scope是否继承$rootScope的属性?AngularJS.