Chapter 9
The original contents of the directive's element, which is going to be
inserted into the template, needs to be associated with the original
scope and not the isolated scope. By transcluding the original elements
we are able to maintain the correct scope for these elements.
Our alert directive is a widget, using isolated scope. Consider what scopes are
created with the alert directive. Before the alert directive has been compiled the
DOM and its scopes look like this:
<!-- defines $rootScope -->
<div ng-app ng-init="type='success'">
<!-- bound to $rootScope -->
<div>{{type}}</div>
<!-- bound to $rootScope -->
<alert type="'info'" ...>Look at {{type}}</alert>
</div>
The
{{type}}
does not have a scope directly defined on it. Instead, it isimplicitly bound to the $rootScope because it is a child of the ng-app element where
$rootScope is defined and so {{type}} will evaluate to 'success'.
On the alert element we have an attribute: type="'info'". This attribute is mapped
to a type property on the template's scope. Once the alert directive has been
compiled, it is replaced with its template, the DOM and its scopes look like this:
<!-- defines $rootScope -->
<div ng-app ng-init="type='success'">
<!-- bound to $rootScope -->
<div>{{type}}</div>
<!-- defines an isolated scope -->
<div class="alert-{{type}}" ...>
<!-- bound to isolated scope -->
<button>...</button>
<div ng-transclude>
<!-- defines new translude scope -->
<span>Look at {{type}}</span>
</div>
</div>
</div>
Inside the template, the class="alert-{{type}}" attribute is implicitly bound to
the isolated scope and so will evaluate to class="alert-info".