角度范围 - 隔离 VS 继承.哪一个更严格 [英] Angular scope - Isolated VS Inherited. Which one is more restrictive

查看:29
本文介绍了角度范围 - 隔离 VS 继承.哪一个更严格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过几个 You Tube 视频并阅读了其他堆栈溢出线程,但仍然无法确定哪个角度范围更具限制性.孤立或继承.从孤立的名称来看,它是否是限制性最强的范围,但由于它允许各种设置,例如@、= 和 &对我来说,它似乎没有继承范围那么严格.

那么问题是哪一个更具限制性,为什么?

解决方案

我敢猜测您对限制性"的定义与对外部范围内的数据的访问有关.

根据该定义,隔离更具限制性.隔离范围不从其父级继承,因此它无法访问在其父级上定义的变量.(您仍然可以通过 scope.$parent.p 访问它们).

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

所以,如果你有以下内容

<isolate p="p1"></isolate><继承的></继承的>

和指令定义为:

.directive("隔离", function(){返回 {范围: {p:="},链接:功能(范围){var p1a = scope.p;//"富"var p1b = scope.p1;//不明确的var p2 = scope.p2;//不明确的}}}).directive("继承", function(){返回 {范围:真实,链接:功能(范围){var p1 = scope.p1;//"富"var p2 = scope.p2;//酒吧"}}}

isolate 指令只会看到 scope.p" - 这是 p1 的代理,inherited` 会看到">

I have seen several you tube videos and read other stack overflow threads but still cannot figure out which one of angular scope is more restrictive. Isolated or Inherited. From the name isolated it feels if it is the most restrictive scope but since it allows various settings like @, =, and & to me it seems less restrictive then inherited scope.

So the question is which one is more restrictive and why ?

解决方案

I'd venture a guess that your definition of "restrictive" has to do with access to data in the outer scope.

With that definition, isolated is more restrictive. The isolate scope does not inherit from its parent and so it does not have access to variables defined on its parent. (you could still access them via scope.$parent.p).

Inherited scope scope: true, creates a child scope that inherits from the parent, and so it has access to all the variables exposed on the parent scope.

So, if you have the following

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

and directives defined as:

.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 directive will only see scope.p" - which is a proxy forp1, andinherited` will "see"

这篇关于角度范围 - 隔离 VS 继承.哪一个更严格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆