给定两个范围 - x,y - 是否有内置函数,如果x是y的祖先,则返回true?
(显然我可以使用$rootScope
从y遍历到$parent
并沿途比较$id
编辑:
与此同时,我使用了这样的东西:
function isChildScope(parentScope, childScope) {
while (childScope) {
if (parentScope.$id === childScope.$id) {
return true;
}
childScope = childScope.$parent;
}
return false;
};
答案 0 :(得分:1)
源代码中的$scope
没有内置方法,所以我怀疑它在其他地方。您可以按照您的说法比较$id
,或者只是x.$parent === y
来检查。
答案 1 :(得分:0)
如果您希望清楚地确定哪个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>