如何从AngularJS中的自定义指令*中使用自己的作用域访问父作用域
我正在寻找任何方式访问“父”范围内的指令。任何范围,转录,要求,从上面传递变量(或范围本身)的组合等。我完全愿意向后弯曲,但我想避免一些完全怪异或不可维持的。例如,我知道现在可以通过从preLink参数获取$ scope并迭代它的$ sibling作用域来找到概念上的“parent”。
我真正想要的是能够在父作用域中观察一个表达式。如果我能做到这一点,那么我可以完成我想在这里做的事: 一个重要的注意事项是该指令必须在同一父范围内可重复使用。因此,默认行为(范围:false)不适用于我。我需要一个单独的范围每个指令的实例,然后我需要看一个变量,生活在父范围。 代码示例值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,parentControl) { // Has my situation improved by the time the postLink is called? } } } }; });
见
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
总结:指令访问其父($ parent)作用域的方式取决于指令创建的作用域的类型: > default(scope:false) – 指令不创建一个新的作用域,所以这里没有继承。指令的作用域与父级/容器的作用域相同。在链接功能中,使用第一个参数(通常是范围)。 上面的链接有所有4种类型的例子和图片。 您不能在指令的编译函数中访问作用域(如此处所述:https://github.com/angular/angular.js/wiki/Understanding-Directives)。您可以在链接功能中访问指令的作用域。 观看: 对于1.和2.上面:通常你通过属性指定指令需要哪个父属性,然后$ watch it: <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() { ... }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |