Domanda

http://plnkr.co/edit/gNOcFFpTxaTJ6Vhbq9Kp?p=preview

Can someone explain me how can 00B be inside 00A

enter image description here

This is the code

<div directive-one="['foo', 'bar']">
    <directive-two />
</div>

where directive_one(00B) has

scope: {
  arr: '=directiveOne' 
}

and directive_two(00A) has no scope param defined. I would have thought directive_two would inherit scope from directive_one, so scope.data would be accesible inside. But for some reason it seems to be the other way around..

È stato utile?

Soluzione

Evaluation scopes in case of isolate directives

The real scope tree is the one you see in your Batarang Chrome Dev Tool extension. Isolate scope does not inherit its outside scope but refers to it with its $parent property.

Since Angular version 1.2.0, the scope of what is written inside an element with an isolate scope directive is evaluated against the outside scope !

The official change log is:

  • $compile:
    • due to d0efd5ee, Child elements that are defined either in the application template or in some other directives template do not get the isolate scope. In theory, nobody should rely on this behavior, as it is very rare - in most cases the isolate directive has a template.
    • due to 909cabd3, Directives without isolate scope do not get the isolate scope from an isolate directive on the same element. If your code depends on this behavior (non-isolate directive needs to access state from within the isolate scope), change the isolate directive to use scope locals to pass these explicitly.

To understand, try this HTML:

<body ng-app="plunker">
  {{$id}} / {{$childId}}
  <div isolate-dir>
    {{$id}} / {{$childId}}
    <div not-isolate-dir>
      {{$id}} / {{$childId}}
    </div>
  </div>
</body>

With the following JS:

angular.module('plunker', [])
.directive('isolateDir', function() {
  return {
    scope: {},
    link: function(scope) {
      scope.$parent.$childId = scope.$id;
    }
  }
})
.directive('notIsolateDir', function() {
  return { };
});

See the Plunker.

There we expose the isolate scope $id outside this scope as the $childId scope property.

Now compare those outputs:

  • Angular version 1.2.0rc1 (< 1.2.0): $childId cannot be read since we wrote it in the scope outside of the isolate scope, and the interpolation strings in isolate element evaluates againts the isolate scope.

002 / 003
003 /
003 /
  • Angular version 1.2.0: the same interpolation strings are evaluated against the outside scope. $scopeId is displayed !

002 / 003
002 / 003
002 / 003


Warning !! this difference does not exist when using directive templates !: using directive templates, you will get the first output.


Your case

directiveTwo does not use the isolate scope even if it is bound to a child of the directiveOne element.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top