🔄 Introduction to Directive Lifecycle in AngularJS
Understand the phases involved in the lifecycle of an AngularJS directive.
Every AngularJS directive goes through a lifecycle that determines how it is created, compiled, linked, and integrated with the DOM and the application’s scope.
📌 Directive Lifecycle Phases
- 1. Compile – Runs once when the directive is matched. Used for DOM transformation.
- 2. Link – Links the compiled template with the scope. Used to add event listeners and manipulate scope-bound behavior.
- 3. Controller (optional) – Provides directive-specific logic and can be shared with other directives via `require`.
- 4. Pre-link and Post-link – Available in advanced scenarios for precise control over linking.
🛠 Example with Compile and Link
app.directive('lifecycleDemo', function() {
return {
restrict: 'E',
compile: function(tElement, tAttrs) {
console.log('Compiling directive...');
return {
pre: function(scope, element, attrs) {
console.log('Pre-linking...');
},
post: function(scope, element, attrs) {
console.log('Post-linking...');
element.on('click', function() {
alert('Directive clicked!');
});
}
};
}
};
});
This directive logs lifecycle stages and attaches a click event in the post linking phase.
📊 When to Use Each Phase
- Compile – For DOM transformation before it is linked with scope.
- Pre-link – Setup that needs to happen before child elements are linked.
- Post-link – Safest place to bind DOM events and final DOM manipulations.
compile function in basic use cases. Start with link for most scenarios.


