为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英3389331 2019-07-09 16:20:16
如何在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?                 }             }         }     };});
查看完整描述

3 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

下面是我曾经使用过的一个技巧:创建一个“虚拟”指令来保存父作用域,并将其放置在所需指令之外的某个地方。类似于:

module.directive('myDirectiveContainer', function () {
    return {
        controller: function ($scope) {
            this.scope = $scope;
        }
    };});module.directive('myDirective', function () {
    return {
        require: '^myDirectiveContainer',
        link: function (scope, element, attrs, containerController) {
            // use containerController.scope here...
        }
    };});

然后

<div my-directive-container="">
    <div my-directive="">
    </div></div>

也许不是最优雅的解决方案,但它完成了任务。


查看完整回答
反对 回复 2019-07-09
  • 3 回答
  • 0 关注
  • 810 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信