如何避免在嵌套范围内使用`$parent.$parent.$parent` [英] How to avoid using `$parent.$parent.$parent` in nested scopes
问题描述
如何知道 Angular 控制器链中的父控制器名称?
我是 Angular 的新手,所以我有一个基本问题.
假设,在 Angular 中,我有一个如下所示的控制器链.
... 父元素中的东西<div ng-controller="childController">... 子元素中的东西
有没有办法在子元素中编写代码,以便我可以在输出中知道父控制器名称(在这种情况下输出应该是'parentController')?
我需要这个,因为我有一个太大的项目,想知道每个控制器的父级,因为有人写了这样的代码
googleOAuth= $scope.$parent.$parent.$parent.$parent.status.googleOAuth
我无法理解所以想知道每个 $scope 的父级.
关于方法是使用controller as"语法:
<!-- ... 父元素中的某些内容--><div ng-controller="childController"><!-- ... 子元素中的某些内容-->{{top.status.googleOAuth}}
这需要使用 this
上下文而不是 $scope
来编写控制器.
另一种方法是使用父作用域中对象的属性:
app.controller("parentController", function($scope) {$scope.top = {状态:{} };$scope.top.status.googleOAuth = 值;});
<!-- ... 父元素中的某些内容--><div ng-controller="childController"><!-- ... 子元素中的某些内容-->{{top.status.googleOAuth}}
因为作用域使用原型继承,top
属性可用于子作用域.
请参阅 AngularJS 开发人员指南 - 范围层次结构.
How can I know the Parent controller name in controller chain of Angular?
I'm new to Angular so I have one basic question.
Suppose, In Angular, I have a controller's chain like below.
<div ng-controller="parentController">
... something in the parent element
<div ng-controller="childController">
... something in the child element
</div>
</div>
Is there any way to write the code in the child element so that I can know the parent controller name in the output (In this case output should be 'parentController')?
I need this because I have a too big project and want to know the parent of each controller because someone has wrote the code like
googleOAuth= $scope.$parent.$parent.$parent.$parent.status.googleOAuth
and I'm not able to understand so want to know the parent of each $scope.
On approach is to use "controller as" syntax:
<div ng-controller="parentController as top">
<!-- ... something in the parent element -->
<div ng-controller="childController">
<!-- ... something in the child element -->
{{top.status.googleOAuth}}
</div>
</div>
This requires the controller be written using the this
context instead of $scope
.
Another approach is to use a property of an object in the parent scope:
app.controller("parentController", function($scope) {
$scope.top = {status: {} };
$scope.top.status.googleOAuth = value;
});
<div ng-controller="parentController">
<!-- ... something in the parent element -->
<div ng-controller="childController">
<!-- ... something in the child element -->
{{top.status.googleOAuth}}
</div>
</div>
Because scopes use prototypical inheritance, the top
property is available to child scopes.
See AngularJS Developer Guide - Scope Hierarchies.
这篇关于如何避免在嵌套范围内使用`$parent.$parent.$parent`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!