Mastering Web Application

(Rick Simeone) #1

Building Your Own Directives


At the linking stage, the scope is being attached to the directive,
and the linking function can then wire up bindings between the
scope and the DOM.

The compile stage is mostly an optimization. It is possible to do almost all the
work in the linking function (except for a few advanced things like access to the
transclusion function). If you consider the case of a repeated directive (inside ng-
repeat), the compile function of the directive is called only once, but the linking
function is called on every iteration of the repeater, every time the data changes.


Transclusion functions are explained in detail in Chapter 9,
Building Advanced Directives

The following table shows what compile functions are called when the AngularJS
compiler matches the directives. You can see that each compile function is only
called once when each directive is used in a template.


Template Compile step
<ul my-dir> myDir compile function
<li ng-repeat="obj in objs" my-dir>
</li>

ngRepeat compile function
myDir compile function
</ul>

The following table shows what linking functions are called when the template is
converted to the final HTML. You can see that the linking function for myDir is called
on every iteration of the repeater:


HTML Linking step
<ul my-dir> myDir linking function
<!-- ng-repeat="obj in objs" -> ngRepeat linking function
<li my-dir></li> myDir linking function
<li my-dir></li> myDir linking function
<li my-dir></li> myDir linking function
</ul>

If you have some complex functionality that does not rely on the data in the scope,
then it should appear in the compile function, so that it is only called once.

Free download pdf