Although directives and attribute widgets appear the same in a
template (ng:init
is a directive, ng:repeat
is an attribute widget), there is a difference in
the order in which they are evaluated. The user of existing directives or widgets cannot determine
the order of evaluation. The evaluation order is the responsibility of the developer creating
custom directives and widgets.
For example, consider this piece of HTML, which uses the ng:repeat
, ng:init
, and ng:bind
widget and directives:
<ul ng:init="people=['mike', 'mary']"> <li ng:repeat="person in people" ng:init="a=a+1" ng:bind="person"> </li> </ul>
Notice that the order of execution matters here. Because we want to run the ng:init="a=a+1
and
ng:bind="person"
once for each person in people
, we need to execute ng:repeat
to make copies of the <li>
element before we run the
ng:init
, and ng:bind
for each of the <li>
copies.
If you implemented ng:repeat
as a directive, there would be no guarantee that the attributes
ng:repeat
, ng:init
, and ng:bind
would be evaluated in the order they are declared, because
the order of element attributes in HTML is not significant to the browser.
So, when creating a custom HTML attribute, you will have to consider whether a directive or a widget is more appropriate. When the order of execution doesn't matter, directives are the right choice. In a situation where the order matters and one attribute should be processed with a higher priority than others, use a widget for the attribute that must be processed first.