Manipulating the DOM with a Compile Function

The compile function is very similar to the link function with one major advantage, but several drawbacks. The advantage and really the main reason to use the compile function is performance. The compile method is executed only once when compiling the template, whereas the link function is executed each time the element is linked, for example, if you are applying multiple directives inside an ng-repeat loop or when the model changes. If you are doing a large number of DOM manipulations, that can be a big deal.

These are the limitations of the compile function:

■ Any manipulations are applied before cloning takes place. That means that when the custom directive is used inside an ng-repeat, any DOM manipulations ...

Get Learning AngularJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.