4

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?

1
  • Is the numberFormatter directive based on the $parsers/$formatters chain (as it should be)? Commented May 27, 2015 at 11:32

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

(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).

2 Comments

Seems fair to assume the question isn't about priority. Certainly sounds less like it the more I read it, +1
Actually I had started writing about priority myself, then I noticed the detail!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.