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

ε祈祈猫儿з 提交于 2019-12-12 02:06:46

问题


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 ?


回答1:


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"




回答2:


Isolated is more restrictive as you need to manually declare all possible bindings and the way they are boun using @, =, etc.

Using inherited scope, you do not need to declare anything: everything is already available from the parent scope.



来源:https://stackoverflow.com/questions/28866758/angular-scope-isolated-vs-inherited-which-one-is-more-restrictive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!