我正在编写我的angularjs指令,其定义如下:
return {
restrict: 'EA',
link: link,
scope: true,
transclude: true,
replace: true,
controller: controller,
template: '<div class="wizard">' +
'<div ng-transclude></div>' +
'</div>'
};
我注意到创建了两个范围:
< Scope (003) --- parent scope of directive
< Scope (004) --- controller scope of directive which I think is child scope created by 'scope=true'. all my functions, properites defined in controller show up in this scope
< Scope (005) --- transclude scope which is empty
从文档我期望只创建一个子作用域,因为'scope = true'不会创建一个孤立的作用域。这导致所有被'ng-transclude'替换的元素实际上继承了Scope(005)并且无法访问我在控制器中定义的函数/属性,因为它们在Scope(004)中,它是Scope(005)的兄弟。
我不知道出了什么问题,有人可以在这里点灯吗?
使用Chrome调试器观看我的元素时,我注意到这些元素是由“ng-scope”类添加的,但是,如何将“ng-scope”与batarang控制台中显示的范围相匹配?比如show ng-scope的id。
谢谢
答案 0 :(得分:15)
scope: true
将从控制器范围创建一个prototypically inherits的新子范围 - 这是范围004。
scope: { ... }
将创建一个新的子范围,它不会从控制器范围原型继承。
无论哪种方式,都会创建一个新的子范围。
此外,由于您使用的是transclude: true
,因此会创建另一个(已转换的)子范围005。 Transcluded范围始终是原型继承自控制器范围。
正如您已经发现的那样,您在指令范围(即指令内)中定义的属性和函数对视图不可用,因为视图使用了被转换的范围。
上图基于以下代码:
app.directive('myDirective', function() {
return {
restrict: 'EA',
//link: link,
scope: true,
transclude: true,
replace: true,
controller: function($scope) {
$scope.dirProp1 = "dirProp1";
$scope.dirFunc = function() {}
},
template: '<div class="wizard">' +
'<div ng-transclude></div>' +
'</div>'
};
});
function MyCtrl($scope) {
$scope.parentCtrlProp1 = 'ParentCtrlProp1';
}
因此,从图中可以看出,转换范围(因此是被转换的内容)只能通过原型链访问控制器范围(003)上定义的属性和函数。
如何将“ng-scope”与batarang控制台中显示的范围相匹配?比如show ng-scope's 标识。
我不知道有什么方法可以做到这一点(这就是为什么我写了一个工具来绘制我自己的照片)。
答案 1 :(得分:2)
很难找出没有任何jsfiddle的上下文。你的链接功能是什么?你的控制器功能是什么?
顺便说一句,这是正常的行为,因为文档说transclude:true也创建了一个新的范围。
请看这里:https://github.com/angular/angular.js/wiki/Understanding-Scopes
被抄袭的和孤立的范围(如果有的话)是兄弟姐妹 - 每个范围的$ parent属性引用相同的父范围。什么时候 存在transcluded和isolate范围,隔离范围属性 $$ nextSibling将引用被转换的范围。
因此,如果您想要彼此访问2个兄弟姐妹,您必须使用与其父母的双向绑定