The initial setup:
<div ng-app="app">
<clock timezone="MST"></clock>
</div>
var app = angular.module("app",[]);
app.directive("clock", function () {
return {
restrict: 'E',
scope: {
timezone: "@"
},
template: "<div>12:00pm {{timezone}}</div>"
};
});
Directives can be broken into 2 categories, components and containers. The above example directive, clock, would be an example of a component - uncomplicated behavior, essentially display the data passed into the attributes.
<div ng-app="app">
<clock timezone="MST"></clock>
<panel title="I'm a title">
<clock timezone="PST"></clock>
</panel>
</div>
});
app.directive("panel", function () {
return {
restrict: "E",
transclude: true,
scope: {
title: "@"
},
template: "<div style='border: 3px solid #000000'>" +
"<div class='alert-box'>{{title}}</div>" +
"<div ng-transclude></div></div>"
};
});
The panel directive is an example of a container. Panel takes a title attribute from the view, uses @ in the isolate scope to insert it into the template, and uses transclusion to append a clock component from the view into the template after the alert-box title.
Acting as a container allows for differing content inside the container directive when multiple instances of the directive exist:
<div ng-app="app">
<clock timezone="MST"></clock>
<panel title="I'm a title">
<clock timezone="PST"></clock>
</panel>
<panel title="I'm a title">
<clock timezone="PST"></clock>
<clock timezone="PST"></clock>
<clock timezone="PST"></clock>
<clock timezone="PST"></clock>
</panel>
</div>
Here, we are allowed to have separate sets of content, here component directives, within multiple instances of independent container directives.