Several directives provide support for AngularJS functionality. These directives do everything from bootstrapping an application to ensuring that Boolean expressions that AngularJS requires are preserved in the DOM.
Table 6.1 lists these directives and describes the behavior and usage of each.
The directives in Table 6.1 are used in different ways in various parts of the code. You have already seen a few of them such as ngApp
and ngController
used in previous examples. Some are fairly intuitive, such as using ng-src
instead of src
when implementing <img>
elements in a template. Others will be used in various examples in subsequent chapters.
I did want to give you an example at this point of using the ngInclude
directive. This little directive is simple to employ and can be used for a variety of purposes, especially if you are trying to introduce AngularJS into an existing system. In this example we will use ngInclude
to swap the banner bar at the top of a basic web page by loading different partial HTML files from the server.
The code in Listing 6.1 implements a very basic AngularJS controller that stores an HTML filename in a variable named titleBar
. The code in Listing 6.2 implements an AngularJS template that includes a couple of links at the top to switch pages and a <div>
element on line 24 that using ng-include
to change the contents of the div to the file specified by titleBar
.
The different versions of the title bar are located in the files shown in Listings 6.3 and 6.4. Basically, these files just contain a <p>
element that has either the large
or small
class assigned to it. The class definitions are located in the <style>
element of Listing 6.2.
Figure 6.1 shows the two title banners. When the links are clicked to switch banners, the contents of the <div>
element in the original are replaced by the new HTML file being loaded.
01 angular.module('myApp', []).
02 controller('myController', function($scope) {
03 $scope.titleBar = "small_title.html";
04 });
01 <!doctype html>
02 <html ng-app="myApp">
03 <head>
04 <title>AngularJS Data Include Directive</title>
05 <style>
06 .large{
07 background-color: blue; color: white;
08 text-align: center;
09 font: bold 50px/80px verdana, serif;
10 border: 6px black ridge; }
11 .small{
12 background-color: lightgrey;
13 text-align: center;
14 border: 1px black solid; }
15 a{
16 color: blue; text-decoration: underline;
17 cursor: pointer; }
18 </style>
19 </head>
20 <body>
21 <div ng-controller="myController">
22 [<a ng-click="titleBar='large_title.html'">Make Title Large</a>]
23 [<a ng-click="titleBar='small_title.html'">Make Title Small</a>]
24 <div ng-include="titleBar"></div>
25 </div>
26 <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
27 <script src="js/directive_angular_include.js"></script>
28 </body>
29 </html>
01 <p class="small">
02 This is a Small Title
03 </p>
01 <p class="large">
02 This is a Large Title
03 </p>?