AngularJS Directives: Difference between $compile, controller, link functions.

When we develop directives we often use some of these functions. Here I’ll briefly explain differences between them.

The compile function is used for template DOM manipulation and if you need to perform some common calculations for all references of a given directive. It executes in phase when Angular compiles your directive. Compile function doesn’t have scope. So if you have multiple usages of directive on the page the compile function will executes once. In addition the compile function must return link function, since the link attribute is ignored if the compile attribute is defined.

The link function is normally used for registering DOM listeners, $watch expressions on the scope, manipulating of DOM for the current instance(element) of the directive. This function executes in the linking phase, when the data from the $scope is attached to the function and then link function returns the linked html.

The controller function must be used when another directive needs to interact with this directive. So the logic defined in the controller could be shareable with other directives.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this