我正在寻找访问指令中“父”范围的任何方式。范围,超越,要求,从上方传入变量(或范围本身)的任何组合,等等。我完全愿意向后弯腰,但我想避免完全乱码或无法维护的事情。例如,我知道我现在可以通过$scope
从preLink参数中获取并对其$sibling
范围进行迭代以找到概念上的“父级”来做到这一点。
我真正想要的是能够$watch
在父范围内进行表达式。如果我可以做到,那么我可以在这里完成我想做的事情:AngularJS-如何用变量渲染局部变量?
重要说明是,该指令必须在同一父范围内可重复使用。因此,默认行为(作用域:false)对我不起作用。我需要针对指令的每个实例使用一个单独的作用域,然后需要$watch
一个位于父作用域中的变量。
一个代码示例价值1000个字,因此:
app.directive('watchingMyParentScope', function() {
return {
require: /* ? */,
scope: /* ? */,
transclude: /* ? */,
controller: /* ? */,
compile: function(el,attr,trans) {
// Can I get the $parent from the transclusion function somehow?
return {
pre: function($s, $e, $a, parentControl) {
// Can I get the $parent from the parent controller?
// By setting this.$scope = $scope from within that controller?
// Can I get the $parent from the current $scope?
// Can I pass the $parent scope in as an attribute and define
// it as part of this directive's scope definition?
// What don't I understand about how directives work and
// how their scope is related to their parent?
},
post: function($s, $e, $a, parentControl) {
// Has my situation improved by the time the postLink is called?
}
}
}
};
});
总结一下:指令访问其parent($parent
)范围的方式取决于该指令创建的范围的类型:
default(scope: false
)-指令不会创建新的作用域,因此此处没有继承。指令的作用域与父/容器的作用域相同。在链接功能中,使用第一个参数(通常为scope
)。
scope: true
-伪指令创建了一个新的子范围,该子范围从原型上继承自父范围。在父作用域上定义的属性可用于该指令scope
(因为是原型继承)。只需谨防写入原始范围属性-会在指令范围内创建一个新属性(隐藏/阴影相同名称的父范围属性)。
scope: { ... }
-指令创建了一个新的隔离/隔离范围。它不原型继承父范围。您仍然可以使用来访问父作用域$parent
,但是通常不建议这样做。相反,应指定的父范围属性(和/或功能)经由相同的元件上的附加属性,在使用该指令,利用该指令需要=
,@
和&
表示法。
transclude: true
-伪指令创建一个新的“已包含”子作用域,该子作用域通常从父作用域继承。如果该指令还创建了一个隔离范围,那么被包含的和隔离范围就是同级。$parent
每个范围的属性引用相同的父范围。
Angular v1.3更新:如果该指令还创建了一个隔离范围,那么被包含的范围现在是该隔离范围的子级。超越范围和孤立范围不再是同级。现在$parent
,已包含范围的属性引用了隔离范围。
上面的链接提供了所有4种类型的示例和图片。
您不能在指令的编译函数中访问范围(如此处所述:https : //github.com/angular/angular.js/wiki/Understanding-Directives)。您可以在链接函数中访问指令的作用域。
观看:
对于上述1.和2 .:通常,您可以通过属性指定指令需要哪个父属性,然后$ watch:
<div my-dir attr1="prop1"></div>
scope.$watch(attrs.attr1, function() { ... });
如果您正在查看对象属性,则需要使用$ parse:
<div my-dir attr2="obj.prop2"></div>
var model = $parse(attrs.attr2);
scope.$watch(model, function() { ... });
对于上述3.(隔离范围),请注意您使用@
或=
标记赋予指令属性的名称:
<div my-dir attr3="{{prop3}}" attr4="obj.prop4"></div>
scope: {
localName3: '@attr3',
attr4: '=' // here, using the same name as the attribute
},
link: function(scope, element, attrs) {
scope.$watch('localName3', function() { ... });
scope.$watch('attr4', function() { ... });
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句