Mastering Web Application

(Rick Simeone) #1
Chapter 9

We append the transcluded elements to the first

element below the directive's
element. When calling the transclusion function, we bind the transcluded elements
to a scope. In this case we create a new scope, which is a sibling of the directive's
scope, that is, child of the $parent of the directive's scope.


This is necessary when the directive has an isolated scope; since the scope passed to
the link function is the isolated scope and does not inherit the properties from the
parent scope, which the transcluded elements need.


Getting the transclusion function in the directive controller with $transclude

We can access the transclusion function in a directive controller by injecting
$transclude. In this case, $transclude is a function that is pre-bound to new
a child of the parent scope, so you do not need to provide a scope.


controller: function($scope, $element, $transclude) {
$element.find('p').first().append($transclude());
}

Once again, we append the transcluded elements to the first

element.


With $transclude, the pre-bound scope will be a prototypical child
of the original scope from where the transcluded elements came.

Creating an if directive that uses transclusion


Let's look at a simple directive that makes explicit use of transclusion functions
rather than relying on the ng-transclude directive. While AngularJS 1.0 provides
both ng-show and ng-switch directives for changing the visibility of content in an
application, ng-show doesn't remove the element from the DOM when it is hidden
and ng-switch is quite verbose for simple situations.


If we just want to remove the element from the DOM when it is not needed, we can
create an if directive. It would be used similar to ng-show:


<body ng-init="model= {show: true, count: 0}">
<button ng-click="model.show = !model.show">
Toggle Div
</button>
Free download pdf