Maybe it will help to identify how they are related:
compile():
gives you access to the element before it has been inserted into the
DOM. (performance advantage)
returns a link() function.
if you specify your own compile function, you can alternatively return an object with pre and post properties and define your pre-link and post-link functions, as described below.
link():
There are actually two "linking" functions, pre and post.
pre is called after your element has scope, but before actually linking to the document and calling post, angular will recursively compile any child elements. When your element's post link function has been called, all children directives have been compiled and linked. So you'd use pre if you needed to make any changes to the scope before children are compiled and inserted.
post is the function returned from compile() by default and occurs after the element has been inserted into the DOM and the proper scope object has been initialized. At this point, any child directives have been compiled and inserted into your element.
other notes:
when you specify a link() parameter in the directive options:
return {
replace: ...,
scope: ...,
link: function(){...},
};
that function is returned by compile() ( unless you also specify a compile() function, in which case, the link property is ignored ), so if you use the link option, you are saying, "I only need to do stuff after the element has been added to the document and the scope is ready to use."
The same is true when you return a function instead of an options object in your directive; that function is your link() function.
When angular is connecting your directive to your document (when it sees your directive attribute or element in your HTML) it will call the compile() function for the instance it is creating. compile() returns a link() function or an object with pre and post link functions. So say there is a portion of my HTML like so:
<div my-directive class='first'>
<div my-directive class='second'>
</div>
</div>
Let's assume you are assigning your own compile function:
angular.module('myapp').directive('myDirective', function(){
return {
replace: true,
compile: function(){
console.log("i'm compile");
return {
pre: function(){ console.log("i'm pre-link"); },
post: function(){ console.log("i'm post-link"); }
};
}
}
});
when you're app runs you'll see (I added comments for clarity):
"i'm compile" // class = first
"i'm pre-link" // class = first
"i'm compile" // class = second
"i'm pre-link" // class = second
"i'm post-link" // class = second
"i'm post-link" // class = first