小编典典

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

angularjs

我正在寻找访问指令中“父”范围的任何方式。范围,超越,要求,从上方传入变量(或范围本身)的任何组合,等等。我完全愿意向后弯腰,但我想避免某些完全不可靠或难以维护的事情。例如,我知道我现在可以通过$scope从preLink参数中获取并对其$sibling范围进行迭代以找到概念上的“父级”
来做到这一点。

重要说明
是,该指令必须在同一父范围内可重用。因此,默认行为(作用域: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?
                }
            }
        }
    };
});

阅读 292

收藏
2020-07-04

共1个答案

小编典典

总结一下:指令访问其parent($parent)范围的方式取决于该指令创建的范围的类型:

  1. default(scope: false)-指令不会创建新的作用域,因此此处没有继承。指令的作用域与父/容器的作用域相同。在链接功能中,使用第一个参数(通常为scope)。

  2. scope: true-伪指令创建了一个新的子范围,该子范围从原型上继承自父范围。在父作用域上定义的属性可用于该指令scope(因为是原型继承)。只是要谨防写入原始范围属性-它将在指令范围内创建一个新属性(隐藏/阴影同名的父范围属性)。

  3. scope: { ... }-指令创建一个新的隔离/隔离范围。它不原型继承父作用域。您仍然可以使用来访问父作用域$parent,但是通常不建议这样做。相反,应指定的父范围属性(和/或功能)经由相同的元件上的附加属性,在使用该指令,利用该指令需要=@&表示法。

  4. 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() { ... });
2020-07-04