是否有内置的方法来知道范围是否是另一个范围的孩子?
问题描述:
给定两个示波器 - x,y - 是否有内置函数,如果x是y的祖先,则返回true?是否有内置的方法来知道范围是否是另一个范围的孩子?
(我可以明显地从y中穿越到$rootScope
使用$parent
一路上比较$id
)
编辑:
在这期间我使用的是这样的:
function isChildScope(parentScope, childScope) {
while (childScope) {
if (parentScope.$id === childScope.$id) {
return true;
}
childScope = childScope.$parent;
}
return false;
};
答
来源中$scope
没有内置方法,所以我怀疑它是否在其他地方。你可能会像你说的那样比较$id
或简单地用x.$parent === y
来检查。
答
如果您正在寻找清楚地识别controller
一个$scope
属于我建议控制器
<!-- In Your Binding -->
<div ng-controller="MyCtrl as ctrl">
<span>{{ctrl.foo}}</span>
</div>
<!-- In Your Controller -->
app.controller('MyCtrl', function() {
this.foo = "Hello World!";
});
这句法将双重约束的controller
但会使$scope
你的工作有明确界定。
这是嵌套控制器的一个很好的例子,它显示了如何提高可读性。
<div ng-controller="MainCtrl as main">
{{ main.title }}
<div ng-controller="AnotherCtrl as another">
Scope title: {{ another.title }}
Parent title: {{ main.title }}
<div ng-controller="YetAnotherCtrl as yet">
Scope title: {{ yet.title }}
Parent title: {{ another.title }}
Parent parent title: {{ main.title }}
</div>
</div>
</div>
可能,这可能回答这个问题:http://stackoverflow.com/a/13428220/1059101 – Jai 2014-09-04 12:19:51
@Jai - 这个答案没有任何与我的问题......我并不想访问子范围,只要找出一个范围是否是另一个范围的祖先。 – seldary 2014-09-04 12:23:53
所以你想在代码或角铬扩展名为batarang肯定会帮助你。 – Jai 2014-09-04 12:25:39