Mastering Web Application

(Rick Simeone) #1
Chapter 9

The contents of the alert element contains the message to display in the alert. This
needs to be transcluded into the directive's template. A list of alerts can be displayed
using ng-repeat:


<alert type="alert.type" close="closeAlert($index)"
ng-repeat="alert in alerts">
{{alert.msg}}
</alert>

The close attribute should contain an expression that will be executed when the
user closes the alert. The implementation of the directive is quite straightforward
as follows:


myModule.directive('alert', function () {
return {
restrict:'E',
replace: true,
transclude: true,
template:
'<div class="alert alert-{{type}}">' +
'<button type="button" class="close"' +
'ng-click="close()">×' +
'</button>' +
'<div ng-transclude></div>' +
'</div>',
scope: { type:'=', close:'&' }
};
});

Understanding the replace property in the directive definition

The replace property tells the compiler to replace the original directive's element
with the template given by the template field. If we had provided template but not
replace, then the compiler would append the template to the directive's element.


When you ask the compiler to replace the element with a template, it
will copy over all the attributes from the original element to the template
element as well.
Free download pdf