首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在AngularJS中使用自己的作用域*从自定义指令中访问父作用域?

如何在AngularJS中使用自己的作用域*从自定义指令中访问父作用域?
EN

Stack Overflow用户
提问于 2013-07-28 00:47:58
回答 6查看 270.3K关注 0票数 331

我正在寻找在指令中访问"parent“作用域的任何方式。作用域的任何组合,transclude,require,从上面传入变量(或作用域本身)等。我完全愿意倒过来,但我想避免一些完全繁琐或不可维护的东西。例如,我知道我现在可以通过从preLink参数中获取$scope并迭代它的$sibling作用域来找到概念性的“父”。

我真正想要的是能够在父作用域中$watch一个表达式。如果我能做到这一点,那么我就能在这里完成我正在尝试做的事情:AngularJS - How to render a partial with variables?

一个重要的注意事项是,指令必须在同一父作用域中可重用。因此,默认行为(作用域: 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?
                }
            }
        }
    };
});
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17900201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档