Last Updated: February 25, 2016
·
10.73K
· gwwfps

Remember, AngularJS directives can have priorities

This may seem obvious, but when your directive is suddenly hit with a "no controller" error because another directive it depends on is not instantiated, it can be frustrating to debug.

This is especially true when your application was previously running perfectly fine and processing directives in the same order as they appeared in the markup. Don't fall for this trap though, that's just the browsers being nice. The order of attributes does not matter to the HTML spec, so nothing's actually guaranteed.

If your directive actually require another, then it's good to be explicit and declare a priority for it. It can be any number, so just give it a negative value if you want yours to be initialized after all the (regular) built-in directives.

One thing to watch out for is the ngOptions directive. I didn't find anything in the documentation mentioning, but if you go to the source you can see this:

var ngOptionsDirective = valueFn({ terminal: true });

It's declared as terminal, which means on an element where ngOptions is present, all directive processing stops after ngOptions' priority level (which is the default level: 0). So if you have your negative-priority directive on the same element, it won't be used at all. (There are other built-in terminal directives, like ngRepeat, but I think ngOptions is probably the only one where you would want to also have your own directives on the same element.)

For this situation, if you really need ordering, then workarounds have to be used, like storing the options expression in another attribute and compiling an inner element with ngOptions instead.