Angular 范围 - 孤立 VS 继承。哪个更严格

Angular scope - Isolated VS Inherited. Which one is more restrictive

我看过几个 you tube 视频并阅读了其他堆栈溢出线程,但仍然无法弄清楚 angular 范围中的哪一个更严格。孤立或继承。从名称 isolated 来看,它感觉是否是最受限制的范围,但由于它允许各种设置,如 @、= 和 & 对我来说,它似乎比继承范围限制更少。

所以问题是哪一个更严格,为什么?

我猜你对 "restrictive" 的定义与访问外部范围内的数据有关。

根据该定义,孤立的限制更多。隔离作用域不从其父级继承,因此它无权访问在其父级上定义的变量。 (您仍然可以通过 scope.$parent.p 访问它们)。

继承作用域scope: true,创建一个从父作用域继承的子作用域,因此它可以访问在父作用域上公开的所有变量。

所以,如果你有以下条件

<div ng-init="p1 = 'foo'; p2 = 'bar'">
  <isolate p="p1"></isolate>
  <inherited></inherited>
</div>

指令定义为:

.directive("isolate", function(){
  return {
     scope: {
        p: "="
     },
     link: function(scope){
        var p1a = scope.p;  // "foo"
        var p1b = scope.p1; // undefined
        var p2  = scope.p2; // undefined
     }
  }
})
.directive("inherited", function(){
  return {
     scope: true,
     link: function(scope){
        var p1 = scope.p1; // "foo"
        var p2 = scope.p2; // "bar"
     }
  }
}

isolate 指令只会看到 scope.p" - which is a proxy forp1, andinherited` 将 "see"

Isolated 更加严格,因为您需要手动声明所有可能的绑定以及使用 @= 等绑定它们的方式

使用继承作用域,您不需要声明任何东西:父作用域中的一切都已经可用。