Turbocharge Your Web Pages with Angular.js

What is Angular.js? | Examples | SQL Data app | The Angular IDE | W3Schools.com Tutorials | Conclusion

Did you read my piece entitled "The Five Pillars of Web Development?". It gives the impression that all you have to do to build nice-looking and responsive web pages is to write some fancy HTML and add some styles. That's not entirely true.

HTML was originally developed to build static web pages. JavaScript can enhance them to an almost umlimited degree, but it would take a lot of planning to make all of the parts work together. That's called a framework. They can take years to build.

There already is one: It's called Angular.js. Angular is what Google's developers use to provide a consistent user interface, and to enhance productivity; it does both very well. And given that it's free, it's an easy choice.

1. What is Angular.js?

Angular adds features that would have been built in if HTML had been developed from the start for dynamic web page design. It adds declarations that are pre-processed by the Angular.js library. So, for example, ng-model identifies an element that Angular recognizes as a data store, and knows what to do to retrieve its contents, and to reflect changes to the data as it changes. Angular allows you to use declarative html (i.e. new attributes to existing tags) to do most of what you would otherwise have to do using a combination of JavaScript code and Cascading Style Sheet attributes.

Here are a few descriptive blurbs from the Angular/docs website:

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.

With AngularJS, designers can use HTML as the template language and it allows for the extension of HTML's syntax to convey the application's components effortlessly. Angular makes much of the code you would otherwise have to write completely redundant.

AngularJS is maintained by Google, as well as a community of individual developers. The detailed, technical aspects of this framework can be found on the AngularJS website, which states that “AngularJS lets you extend HTML vocabulary.”

Sounds pretty cool, n'est-ce pas?. Let's try it.

2. Examples

You don't have to build a full-blown Angular app. A single link to the Angular javascript file will get you started. Type the following into a text file on your desktop called "Test.html":

Listing 1: Using Angular to display input as it's being typed

<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="">
  <p>Name : <input type="text" ng-model="name"></p>
  <h1>Hello {{name}}</h1>
</div>

</body>
</html>

The screen that results looks pretty plain until you start typing:

screen capture
Fig. 1 - A simple input form using Angular.js

This is pretty spectacular. It's using JavaScript to respond to the KeyDown event; the instant you type, the label below the input box changes. You don't get that with plain ole' HTML.

Note that ng-app is required, even if only initialized to the null string (""). It can also be included in the <body> declaration.

Loading another web page without 'blinking'

A page that loads additional content within the page whenever the user clicks on a particular link is called a single-page app (SPA). It avoids that irritating 'blink' that you see when a page reloads by dynamically rewriting the current page rather than loading entire new pages from a server. If that describes your needs, Angular makes it really easy.

Create three pages called Main.htm, London.htm and Paris.htm, each with a few lines of appropriate HTML content, and maybe an <img> tag and a nice picture. Then, create this page (you can call it SPTest.html) in the same folder:

Listing 2: Loading another web page inside your active page

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/!">Main</a></p>

<a href="#!london">City 1</a>
<a href="#!paris">City 2</a>

<p>Click on the links to read about London and Paris.</p>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.htm"
    })
    .when("/london", {
        templateUrl : "london.htm"
    })
    .when("/paris", {
        templateUrl : "paris.htm"
    });
});
</script>

</body>
</html>

Pretty snappy, eh? Angular has dozens of little tricks like this.

Using Model-View-Controller

Angular uses the Model-View-Controller (MVC) approach to automatic web pages. The easiest way to create an environment for writing and testing web pages is by creating a website using Visual Studio. Open Visual Studio select File, New, Project, and select Empty Web App.

screen capture
Fig. 2 - Creating an empty web project
Then, click on Tools, Nuget Package Manager, Package Manager Console and type
install-package AngularJS

When it finishes, you'll have a Scripts folder with a bunch of javascript files. Add an html page called Index.html and a JavaScript file called Scripts.js in the website root folder. In Scripts.js, drag the Angular.js filename from the Scripts folder created by the installation of AngularJs. It will create a commented entry that will be used by Intellisense:

/// <reference path="scripts/angular.js" />

Next, type this in:

var myApp = angular.module("LesterBob", []);
myApp.controller("LesCtrlr", function ($scope) {
 $scope.message = 'A string that was assigned in a controller.';
});

Doesn't look like much, but you have to have an app name (LesterBob in this case) to tell Angular that you have an app, and a controller name (LesCtrlr in this case) to hold your variables (that's what message is here). You gotta have those two things.

You can also add a style sheet. Right-click on the project and select Add, New Item, Style Sheet and name it Styles.css. Edit it and add just this one line:

body { font-size: 14pt; }

In our html file we'll add a link to Styles.css, and everything in the page will use 14 point type.

Finally, just to demonstrate the ng-include feature works, create an html file called list.html, containing just these five lines of html:

<ul>
  <li>One
  <li>Two
  <li>Three
</ul>

Now, open Index.html and enter this:

Listing 3a - Index.html

<!DOCTYPE html>
<html ng-app="LesterBob">
<head>
<title>Simple Angular page</title>
</head>
<body>
  <div ng-controller="LesCtrlr">
    <br />
    {{ message }} <br />
    {{ ['Sam', 'Charlie', 'Melissa'][1] }} <br />
    2 + 2 = {{ 2 + 2 }} <br />
    <div ng-include="'list.html'" />
  </div>
</body>
</html>

All that's missing is links to all of those little files. So drag Scripts/Angular.js from the Scripts folder created by the NuGet operation to just below the <Head> tag, and then just below that, drag Scripts.js, which is in the website folder. Finally, drag the Styles.css folder below the two Script tags (note that stylesheets are included via Link tags). If you did it right, these three lines will have been added:

  <script src="Scripts/angular.min.js"></script>
  <script src="Script.js"></script>
  <link href="Styles.css" rel="stylesheet" />

At this point, Index.html should look like this:

Listing 3b - Index.html with script references added

<!DOCTYPE html>
<html ng-app="LesterBob">
<head>
  <script src="Scripts/angular.min.js"></script>
  <script src="Script.js"></script>
  <link href="Styles.css" rel="stylesheet" />
  <title>Simple Angular page</title>
</head>
<body>
  <div ng-controller="LesCtrlr">
    <br />
    {{ message }} <br />
    {{ ['Sam', 'Charlie', 'Melissa'][1] }} <br />
    2 + 2 = {{ 2 + 2 }} <br />
    <div ng-include="'list.html'" />
  </div>
</body>
</html>

The body contains a div that assigns our little controller defined above as the ng-controller, which works because the <html> tag at the top assigns "LesterBob" as the ng-app.

So what did this get us? It gives us the ability to do use Angular attributes, which look like the attributes inside many html tags, but do a lot more. Essentially, they pass parameters to JavaScript in Angular.js, which do all kinds of userful things. They can also be used to attach event handlers. So you don't have to write and debug JavaScript, as long as you can find an Angular attribute that calls a JavaScript function that does what you need.

I've included an example: ng-include, which inserts the contents of the named html file directly into the html of the page - note the double and single quotes around the filename. There are many many other Angular attributes, like ng-repeat, which simulates a for-next loop.

At the simplest level, you can do calculations just by enclosing expressions in double curly braces. The line

{{ 2 + 2 }}
immediately evaluates to 4. That's not particularly useful, but being able to write an expression and see the result displayed without having to write JavaScript comes in pretty handy.

3. SQL Data app

Real-world applications usually need to display data retrieved from a database. This is where Angular has some definite advantages. Most of the work involves building the website so that different pages can be displayed using routing. MVC (Model-View-Controller) does a pretty good job, and also provides a data management framework - Entity Framework, which in effect provides intellisense for SQL SELECT statements. So we'll start with a database and an MVC app, and then add an Angular page.

Open SQL Server Management Studio and create a database called Test. Add the following table:

Listing 4 - SQL CREATE TABLE script

CREATE TABLE Member (
 MemberID  INT         NOT NULL IDENTITY(1,1) PRIMARY KEY,
 FirstName VARCHAR(20) NOT NULL DEFAULT '',
 LastName  VARCHAR(20) NOT NULL DEFAULT '',
 Phone     VARCHAR(20) NOT NULL DEFAULT '',
 Email     VARCHAR(40) NOT NULL DEFAULT '')

Use Edit Top 200 Rows to enter a few names:

Fig. 3 - add a few members

Now, open Visual Studio and select File, New, Web , ASP.NET Web Application:

Fig. 4 - Creating a Web project

Select MVC, and be sure to check Web API.

Fig. 5 - Selecting options

The resulting project is pretty big, given that all you want is a few rows of data:

Fig. 6 - The MVC project
But the framework provides for a few other things that you'll need, like routing, so we'll take it.

You'll need to add AngularJS, using NuGet. From the IDE menu, select Tools, Nuget Package Manager, then the first option, Package Manager Console. When the window opens, type install-package AngularJS. After a minute or so, you'll see a bunch of Angular files added to your Scripts folder.

Fig. 7 - After adding the Angular files

The only ones you really need are Angular.js and Angular.Routing.js, but I had to choose between quick-and-dirty and slow-and-clean.

Next, we need to create the data model that the controller will use to return data. Select the Project name in Solution Explorer and select Add, New Item, ADO.NET Entity Data Model, and use the dialogs that follow to select the Member table from the Test database that you created. The model name doesn't matter, so Model1 is fine. EF designer from database is the option you want. Pick your Test database to create the connection string that will be used to connect to the database, and select the Member table. After a minute or two, you'll find Model1.edmx in the Models folder. The generated code in that group of files is what retrieves your Members data.

MVC works through Views and Controllers. A View is like a web page; a Controller is like code-behind.

Right click on your Controller folder and select Add, click Controller, select MVC 5 Controller- Empty and name it MemberController. Here's what you'll get:

Listing 5 - MemberController.cs (in the Controllers folder

public class MemberController : Controller
  { //
  // GET: /Member/
  public ActionResult Index()
  {
    return View();
  }
  }

Right click on the Index method in MemberController, then select Add View, and follow the instructions. A folder called Member will be created under the View folder, and a file named Members.cshtml will be created, with a little placeholder code:

Views/Member/Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
We'll be replacing the contents of this file shortly, so don't obsess over what it's doing. It's keeping your place in line.

You're going to need another folder called ScriptNg, so select the project name in Solution Explorer, right-click and select Add, New folder, and name it ScriptNg. We'll add some content later.

Adding an API controller

If you don't have a folder called API, add one now. Right-click on the API folder and select Add Web API 2 Controller-Empty. Name it MemberController. Open it and type this in:

Listing 6 - MemberController.cs

Public class MemberController : ApiController
  { TestEntities mgr = null;
    public MemberController()
    {  mgr = new TestEntities();  }
    public List<tbl_Member> GetMembers()
    {  List<tbl_Member> Members = null;
       try   { Members = mgr.tbl_Member.ToList(); }
       catch { Members = null; }
       return Members;
    }
  }

Checking your data source

Press F5 to run the website. Something like http://localhost:12345 will appear as the browser url. Add "API/Member/GetMembers and you should see your data:

Fig. 8 - Data returned by the API

Adding AngularJS

Add a folder called ScriptsNg, containing three folders: