Search code examples
javascriptangularjsangularjs-scopeangular-directive

What is the order of multiple directives execution?


Let's say I want to create a new directive with an isolated scope that interacts with the input element, which already has ng-model. How can I be sure if ng-model will bind to right scope.

<input name="first_input"  type="text"  mydir-mod="compare"  mydir-main ng-model="hi"/>

As you can see here http://plnkr.co/edit/SGhOSx?p=preview mydir-main creates isolated scope. Which scope ng-model will choose to bind? Does this depend on order? How order is determined? Why mydir-mod always executes before mydir-main?


Solution

  • There is a priority property that you can set.

    Here is a snip 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.