Directive Priority in AngularJS
Recently I discovered that every directive in AngularJS has a priority score assigned to it. While the page is loaded the priority plays a very important role in setting the order of the execution of various directives in single DOM Element. The priority is used to sort the directives before their “compile” function gets called. In simple words, the execution of directives is done in order of its priority score. Let us understand this using an example:
[javascript]
//Directive Definition
angular.module(‘customDirectives’, [])
.directive(‘directive1’, function () {
return {
restrict: "A",
priority: 100,
compile: function (element, attributes) {
console.log("This is directive with priority 100.")
}
}
}).directive(‘directive2’, function () {
return {
restrict: "A",
priority: 200,
compile: function (element, attributes) {
console.log("This is directive with priority 200.")
}
}
});
[/javascript]
[html]
<p directive1="" directive2=""></p>
[/html]
Now if we use the directives defined on the top with above HTML we get following output in console.
This is directive with priority 200. This is directive with priority 100.
You can set the priority of custom directive by defining the “priority” attribute of the directive object (as shown in the example above) and when the priority is left undefined then it is set to the zero by default. Also, in case of same priority the directives are executed in the alphabetical order.
For knowing the priority score of predefined directives please refer to their angular documentation.
Hope you find this blog useful.
Read Further on AngularJS Series
- AngularJS : A “Write Less Do More” JavaScript Framework
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Adding Items to a JavaScript List and updating corresponding DOM Dynamically
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS