Mastering Web Application

(Rick Simeone) #1
Chapter 8

Let's look at how this directive could be implemented:


myModule.directive('button', function() {
return {
restrict: 'E',
compile: function(element, attributes) {
element.addClass('btn');
if ( attributes.type === 'submit' ) {
element.addClass('btn-primary');
}
if ( attributes.size ) {
element.addClass('btn-' + attributes.size);
}
}
};
});

We are assuming that we have a myModule module already defined.

The name of our directive is 'button' and it is restricted to only appear as an
element (restrict: 'E'). This means that this directive will be applied whenever
the AngularJS compiler comes across the button element. In effect, we are adding
behavior to the standard HTML button element.


The only other part of this directive is the compile function. This function will be
called whenever the compiler matches this directive. The compile function is passed
a parameter called element. This is a jQuery (or jqLite) object that references the
DOM element where the directive appeared, in this case, the button element itself.


In our compile function we simply add CSS classes to the element. based on the
values of the attributes on the element. We use the injected attributes parameter to
access the value of the attributes on the element.


We can do all these modifications in the compile function rather than the linking
function because our changes to the element do not rely on the scope data that
will be bound to the element. We could have put this functionality into the linking
function instead, but if the button appears in an ng-repeat loop, then addClass()
would be called for each iteration of the button.


See Following the directive compilation life-cycle section for a detailed
discussion of this.
Free download pdf