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

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

我正在寻找在指令中访问“父”范围的任何方式。任何范围的组合,转换,要求,从上面传入变量(或作用域本身)等等。我完全愿意向后弯曲,但我想避免一些完全不牢靠或无法维护的东西。例如,我知道我现在可以通过$scope从预链接参数中迭代它的$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?
                }
            }
        }
    };});


慕桂英3389331
浏览 813回答 3
3回答

摇曳的蔷薇

下面是我曾经使用过的一个技巧:创建一个“虚拟”指令来保存父作用域,并将其放置在所需指令之外的某个地方。类似于:module.directive('myDirectiveContainer',&nbsp;function&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;controller:&nbsp;function&nbsp;($scope)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.scope&nbsp;=&nbsp;$scope; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;};});module.directive('myDirective',&nbsp;function&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;require:&nbsp;'^myDirectiveContainer', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;link:&nbsp;function&nbsp;(scope,&nbsp;element,&nbsp;attrs,&nbsp;containerController)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;use&nbsp;containerController.scope&nbsp;here... &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;};});然后<div&nbsp;my-directive-container=""> &nbsp;&nbsp;&nbsp;&nbsp;<div&nbsp;my-directive=""> &nbsp;&nbsp;&nbsp;&nbsp;</div></div>也许不是最优雅的解决方案,但它完成了任务。
打开App,查看更多内容
随时随地看视频慕课网APP