Reputation: 55729
If I have a number of directives applied to an element in AngularJS, in what order will they be executed?
For example:
<input ng-change='foo()' data-number-formatter></input>
Will the number formatter or the change event be fired first. Is it deterministic?
Upvotes: 4
Views: 1303
Reputation: 40296
(This question is not about the priority
setting, it is about the execution of the directives, not the compilation.)
If the number-formatter
directive is based on the standard $parsers
/$formatters
chain, then I believe the order is guaranteed to be formatter/parser first, ng-change
after. Even if you specify ng-model-options="{updateOn: 'change'}"
the order remains the same.
A fiddle: http://jsfiddle.net/4dtnvrbh/ (do experiment with the various ng-model-options
and watch the console).
Upvotes: 1
Reputation: 172378
The docs says:
When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.
Also
Pre-linking function: Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking.
Post-linking function: Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
Upvotes: 2
Reputation: 78525
The order in which directives are compiled is directly based on their priority
:
From the docs:
When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.
Upvotes: 5