Directive Priority in AngularJS

28 / May / 2015 by Gaurav Sharma 0 comments

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

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *