Working with AngularJS Modules and Services: Preparing the Example Project

To prepare for this chapter, I deleted the contents of the angularjs web server folder and installed the angular.js, bootstrap.css, and bootstrap-theme.css files, as described in Chapter 1. I then created a file called example.html, which you can see in Listing 18-1.

Listing 18-1. The Contents of the example.html File

<!DOCTYPE html>

<html ng-app=”exampleApp”>


<title>Services and Modules</title>

<script src=”angular.js”></script>

<link href=”bootstrap.css” rel=”stylesheet” />

<link href=”bootstrap-theme.css” rel=”stylesheet” />


angular.module(“exampleApp”, [])

.controller(“defaultCtrl”, function ($scope) {

$ = {

cities: [“London”, “New York”, “Paris”], totalClicks: 0


$scope.$watch(‘data.totalClicks’, function (newVal) {

console.log(“Total click count: ” + newVal);



.directive(“triButton”, function () {

return {

scope: { counter: “=counter” },

link: function (scope, element, attrs) {

element.on(“click”, function (event) {

console.log(“Button click: ” +;

scope.$apply(function () {









<body ng-controller=”defaultCtrl”>

<div class=”well”>

<div class=”btn-group” tri-button

counter=”data.totalClicks” source=”data.cities”>

<button class=”btn btn-default”

ng-repeat=”city in data.cities”>




<h5>Total Clicks: {{data.totalClicks}}</h5>




This example is based around three button elements, which are generated by the ng-repeat directive from a list of city names defined on the scope by the controller. There is a triButton directive that handles click events from the button elements and updates a counter that is defined by the controller and is data bound via an isolated scope.

This is a totally pointless example in and of itself, but it has some key characteristics that will allow me to demonstrate some important features in the sections that follow. You can see how the example appears in the browser in Figure 18-1.

Each time a button is clicked, messages are written to the JavaScript console (which you can access through your browser’s F12 developer tools) by the controller and the directive, like this:

Button click: London

Total click count: 1

The total number of clicks is also displayed via an inline binding expression in the HTML markup (and can be seen in the figure).

Tip A message will also be written to the console by the controller when the application is first loaded into the browser. This is because I have used the scope $watch method (described in Chapter 13) whose handler function is triggered when the watcher is first set up.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *