【发布时间】:2014-10-24 15:29:54
【问题描述】:
最好用几个小提琴来解释。我在两者中都使用了这些简单的指令:
var demo = angular.module('demo', []);
demo.directive('redBox', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div class="bg-red size-med"><b>I am inside a red box.</b><div ng-transclude></div></div>'
}
});
demo.directive('blueBox', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div class="bg-blue size-med"><b>I am inside a blue box.</b><div ng-transclude></div></div>'
}
});
function MyCtrl ($scope) {
};
我将这两个都包括在内,并在Fiddle #1 中打印范围ID。这如我所料 - redBox 和 blueBox 的范围都是 MyCtrl 范围的子级。
<div ng-app='demo'>
<div ng-controller='MyCtrl'>
My scope's id is {{$id}}. <br/> My parent scope's id is {{ $parent.$id }}.
<red-box>
My scope's id is {{$id}}. <br/> My parent scope's id is {{ $parent.$id }}.
</red-box>
<blue-box>
My scope's id is {{$id}}. <br/> My parent scope's id is {{ $parent.$id }}.
</blue-box>
</div>
</div>
在Fiddle #2 中,我只是在其中一个div 的内容中添加了一个标签。这改变了范围层次结构!即使它们没有嵌套,一个指令的范围也是另一个指令的父级。
这里发生了什么?这如何改变范围的父子关系?
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope