Last week, a colleague asked me if there is a way to control the order in which your Angular.js Directives get executed.
Of course you can! Every directive has a ‘priority’ property. When there are multiple directives defined on a single DOM, the priority is used to sort the directives before their compile functions get called. Directives with greater numerical priority are compiled first. The default priority is 0.
An example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
(function (module) { | |
var passwordMatchDirective = function () { | |
return { | |
restrict: 'A', | |
scope: true, | |
require: 'ngModel', | |
priority: 1002, | |
link: function (scope, elem, attrs, control) { | |
var checker = function () { | |
var e1 = scope.$eval(attrs.ngModel); | |
var e2 = scope.$eval(attrs.passwordMatch); | |
return e1 == e2; | |
}; | |
scope.$watch(checker, function (n) { | |
control.$setValidity("unique", n); | |
}); | |
} | |
}; | |
}; | |
module.directive("passwordMatch", passwordMatchDirective); | |
}(angular.module("commonModule"))); |