From the doc of angularjs, when defining a directive, there's a postLink
in compile
, and a postLink
in link
myModule.directive('directiveName', function factory(injectables) {
var directiveDefinitionObject = {
priority: 0,
template: '<div></div>',
templateUrl: 'directive.html',
replace: false,
transclude: false,
restrict: 'A',
scope: false,
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
},
link: function postLink(scope, iElement, iAttrs) { ... }
};
return directiveDefinitionObject;
});
What's the difference between them? I notice the postLink
in link
has a argument less than the one in compile
. And are there any other difference?
Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Post-linking function Executed after the child elements are linked.
AngularJS Directive's replace option can be used to replace the container element itself by directive content. By default, the directive content inserted as the child of the element directive is applied on. But using replace, that container element altogether can be replaced by directive's actual content HTML.
Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.
Compiler is an AngularJS service which traverses the DOM looking for attributes. The compilation process happens in two phases. Compile: traverse the DOM and collect all of the directives. The result is a linking function. Link: combine the directives with a scope and produce a live view.
They're no different, what you have there is just psuedo-code from the documentation. The postLink function is just the most important one, so there are a variety of ways to declare it.
Here is a Plunker as an example...
... and here is some psuedo code showing the different declarations of a postLink function:
app.directive('dir1', function () {
return function(scope, elem, attr) {
//this is the same
};
});
app.directive('dir2', function () {
return {
link: function(scope, elem, attr) {
//this is the same
}
};
});
app.directive('dir3', function () {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, elem, attrs) {
//this is the same
}
}
}
};
});
... you only need one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With