Directives can be Angular predefined or custom directives. They can be very simple or extremely complicated. Getting a solid understanding of Directives is necessary to be a good Angular developer.
Each directive undergoes a "life cycle" as Angular compiles and links it to the DOM.
In a directive’s life cycle, there are four distinct functions that can execute if they are defined. Each enables the developer to control and customize the directive at different points of the life cycle. The four functions are
- compile
- controller
- pre-link
- post-link
The compile function allows the directive to manipulate the DOM before it is compiled and linked thereby allowing it to add/remove/change directives, as well as, add/remove/change other DOM elements.
The controller function facilitates directive communication. Sibling and child directives can request the controller of their siblings and parents to communicate information.
The pre-link function allows for private $scope manipulation before the post-link process begins.
The post-link method is the primary workhorse method of the directive.
Commonly the directive is defined as
.directive("directiveName",function () {
return {
controller: function() {
// controller code here...
},
link: function() {
// post-link code here...
}
}
})
The execution order of the functions within a directive and relative to other directives:
<div parentDir>
<div childDir>
<div grandChildDir>
</div>
</div>
</div>
No comments:
Post a Comment