Category Archives: Uncategorized

AngularJS Basics Part 3: Routing

In our last installment, we built a very simple Angular application from the ground up. In this post, I’ll focus in on AngularJS routing.

Routing is the process of connecting URL paths in your application to the view(s) and controller(s) that make that endpoint come alive. The views (typically HTML) and controllers (Angular-enhanced javascript are preloaded when the user first hits the web site, and for each URL in your application, the routing process dynamically combines the specific views and controllers you specify. It’s how Angular constructs a page, in contrast to the older style of web-database application servers like PHP, ASP.NET or Coldfusion, where the back-end server calculates would what the page should look like based on the URL and send back a pre-digested chunk of HTML (perhaps with relatively minor javascript thrown in for enhanced interactivity).

From a programming perspective, there are many possible ways to structure web applications in general, and more specifically many potential ways to structure an Angular application. In practice, most of the time most developers will pick a basic, tried-and-true application structure. Part of the “basics” for a small-to-medium size Angular app will include a straightforward routing mechanism like ngRoute, a module provided by the AngularJS team. There are other popular routing modules like the open source ui-router, which is a more powerful router generally used in larger applications with more complex routing needs (most notably nested views and a more powerful state-based routing approach).

Let’s look at the code below in some detail. The various sections of interest are separated by javascript comments. In our sample app we used ngRoute to create a default route we called “home”; this route was based off the “/” path which represents the root URL of our application (by “root” URL we just mean there is nothing in the URL after the domain name besides a slash). For that route, we specify the URL of the template (view) file as “homeView.html” and the associated controller as “myAppController”. Notice that the controller, in contrast to the template, is not defined by its URL but rather by name. In this case, the name is defined in the bottom block which defines myAppController.

// start angular module (app) definition
// end angular module (app) definition

// start config block with routing definition
 .config(function($routeProvider) {
   .when('/', {
    templateUrl: 'homeView.html',
    controller: 'myAppController'
// end config block with routing definition

// start definition of controller "myAppController"
 .controller('myAppController', function($scope) {
  $scope.user = {};
  $scope.user.firstName = 'Joe';
// end definition of controller "myAppController"

To add more routes, we would chain more when calls to our $routeProvider configuration. The last route (“/about”) also demonstrates how we can also specify templates and controllers directly inline, on a route by route basis, using the template property to pass in a string instead and by providing a controller function directly instead of referring to an external controller by its name string.

At the end, we chain the otherwise call to provide a default route when no other route matches. In this case, we tell ngRoute to redirect to the “/” root URL as our fallback.

// end angular module (app) definition
// start config block with routing definition
 .config(function($routeProvider) {
   .when('/', {
      templateUrl: 'homeView.html',
      controller: 'myAppController'
   .when('/userList', {
      templateUrl: 'userList.html',
      controller: 'myAppListController'
   .when('/about', {
      template: '<div>Thanks for visiting {{message}}</div>',
      controller: function($scope){
        $scope.message = 'our beautiful web site.';
       redirectTo: '/'

// end config block with routing definition

While this blog gives you a starting point for exploring Angular’s ngRoute system, there is a lot more functionality possible. For example, templates can also be furnished by using a function that returns the template string; routes can be conditionally accessed based on whether or not a function permits access (useful for security measures such as a forced login system); and you can pass parameters in via url to create REST-ful interfaces. And lots more! To learn more, spend some time looking at the ngRoute docs on the official AngularJS site. If you’d like to explore more advanced routing possibilities and are at least somewhat familiar with the computer science concept of state machines, take a look at ui-router, the most popular 3rd party routing module that developers often substitute for ngRoute.

AngularJS Basics Part 2: Views, Model, Scope, Databinding and Controllers

Let’s dive right in.

Copy-paste the following code into your favorite editor, save it as index.html on your computer or a server, and load it up using a web server (this does assume at least a bit of familiarity with Javascript and web servers already, so if this part does not make sense, you’ll probably want to research some basic Javascript before moving on). For convenience, we’ve created a Plunker demo that shows this code in action.


  <script src=""></script>
  <script src=""></script>
  <script src="script.js"></script>
<body ng-app="myApp">
  <div ng-view></div>


// declare the angular application first (a module 
// we shall call "myApp") and declare our dependencies
// (here we have just one dependency which is ngRoute, 
// Angular's default routing service)
 .config(function($routeProvider) {
   .when('/', {
    templateUrl: 'homeView.html',
    controller: 'myAppController'
 .controller('myAppController', function($scope) {
  $scope.user = {};
  $scope.user.firstName = 'Joe';


Hi. HomeView.html here. Please enter user’s first and last name.
I’ve provided an initial first name for you.

User first name:
User last name:

Ok, so far I have:

First name: {{user.firstName}}
Last name: {{user.lastName}}

Looks pretty basic. But so far this code does three important things.

1) First, in our index.html file, we use <script> tags to load the core AngularJS code, as well as the ngRoute module (that’s inside the angular-route.js file).

2) Look more closely, and you’ll notice we reference the ng-app “directive” in the opening <body> tag, which tells Angular that every thing between the opening and closing </body> tag belongs to the Angular module called “myApp” — which we will create shortly and which will form the core of our Angular program.

3) We also inserted the ng-view directive in the <div> tag inside the body. “Directive” may be a new word for you — you can think of it as an additional feature or enhancement Angular adds to the HTML. Directives are scanned by Angular and link to some javascript-driven functionality specific to that directive. Directives starting with “ng” are Angular-native directives; you will learn how to create your own custom directives later.

Now in this case, the ng-view directive tells Angular that the ng-view functionality will apply to this div tag; the ng-view more specifically indicates that this div is a placeholder for our dynamic views that we are going to switch in later. It’s a placeholder the ngRoute module will fill out later for us.

4. In our script file (“script.js”) we declare our Angular module (“myApp” — the same name we declared in our HTML file) and declare a dependency upon ngRoute. ngRoute is Angular’s routing module which ties specific urls to a combination of view and controller (technically, it can do a bit more, but that’s a reasonably simple starting point for us). Upon seeing this declaration, Angular knows we want to use the ngRoute module later in our code.

5. Angular programs are constructed using blocks. In our simple program here, we use a configuration block (it’s the block starting with “.config”) and we declare a controller (it’s the block starting with “.controller”).

6. We declare a route in our config block. To accomplish this, we tell Angular we want to use ngRoute. In the config block we do this by asking Angular for the “$routeProvider” depedency. Then we pass in a function which becomes our config block. Inside that function, we call the $routeProvider, and tell it that when the route is equal to “/” (that’s the top level url of our app) we want to pull in the controller called “myAppController” and combine that with the view file “homeView.html”.

7. Let’s bring up our javascript code and create a super simple model to play with. “Model” is a general programming term to describe some combination of data and functional logic necessary to represent objects of interest in our system. For instance, in a todo-list app, we might create models for creating and editing todo lists and todo items. In an address book application, we might create a model to create and edit contacts (along with their addresses). Here, we’ll just model a very simple “user” with a first and last name. We create that model inside our controller “myAppController”.

8. Our model is created as a property of a special Angular variable called $scope. $scope is a very rich topic in Angular, so for let’s just keep it simple for now by saying that for every controller we create, we ask Angular to pass us in this special $scope variable. And then that $scope variable is actually a Javascript object that will serve as the bag to hold all the variables, objects and functions we want to expose to the view associated with that controller. In this case, the view connected to this controller will be the homeView.html file we declared in our config block above. So on this $scope variable, we just declare an empty object called “user” which we then attach a single property to called “firstName”; once we’ve done that, the user object will be available in our view with a valid firstName property. Here we create a default value of “Joe” for the firstName property so we’ll have something to kick off our view.

9. Now in our view file, we add in a couple of inputs to allow us to edit our user’s first and last name. We use the ng-model directive to tell Angular to which scope variable or property each input should be connected. In this case, we connect the first one to $scope.user.firstName and the second to $scope.user.lastName; now notice we omit the $scope prefix — it’s implicitly there already — and we simply declared the lastName property on our $scope.user object (unlike the $scope.user.firstName property which we explicitly declared in our controller). Angular will allow us to create properties directly on $scope objects we already declared; similarly we could directly create properties on $scope (e.g. if we connected an input to an ng-model=”xyz” it would create a property called $ as soon as we defined that property by typing something).

10. Finally we demonstrate some of the most exciting Angular magic — namely, two-way databinding. When we run this program and start typing something in the first name and last name inputs, what we type gets picked up by Angular (though a Javascript event handler it creates automatically) and almost immediately attached to the corresponding $scope variable through what’s called the digest process. We then see that value immediately reflected back to us because in our html we told Angular to show us the user’s first name (“{{user.firstName}}”) and last name (“{{user.lastName}}”). If you’re familiar with popular javascript library jQuery, you’ll recognize that we accomplished this without actually writing an event handler ourselves; that’s part of what makes Angular such an appealing system for rapid web-application development.

Wow! A lot of concepts packed into a very tiny app. In our next posts we’ll take a more detailed look at routes, directives and integrating CSS in an Angular-aware way.

AngularJS Basics Part 1: the Model-View-Controller approach

You may have heard of the Model-View-Controller paradigm from previous programming experience in other languages.

It’s a way to organize and think about your programs that is designed to make programs easier to develop and maintain over time, especially as application complexity grows.

The MVC model is an example of what computer scientists and developers call a design pattern. It’s not a concept specific to Angular, but rather an approach to program architecture which has been implemented successfully across a variety of programming languages and environments, and which has been found to yield some good practical efficiencies as a time-tested design.

The team that created Angular has baked this concept into Angular’s in many ways and therefore – it makes a lot of sense to go with the rather sensible flow. Let’s take a look at this awesome pic which lays it all out:
Model-View-Controller (MVC) diagram from

This diagram represents the way most event-driven programming is modeled these days. It represents how modern web applications are architected, as well as how typical iOS (iPhone/iPad) and Android applications are built, and how many desktop applications are built as well. As far as web development goes, it represents a break from the jQuery-style of development which intimately ties business logic into the view (typically by tying it into the browser’s Document Object Model).

In MVC, the controller is the chunk of code the coordinates between the model and the various views. The model is the combination of core business logic code and persistent data (data stored in a database, or through some other kind of persistence mechanism for long-term data storage) that make up the “things” represented in the system. The model would thus contain users, user data, and active media assets such as editable files or information — for most web sites, this boils down to the long term data associated with a user account.

The model is responsible for maintaining the integrity of its own data. On a smaller web site, it could consist of tables in a single database. On a larger site, it could consist of many databases, a full API (application programming interface) and a bunch of back-end code written by some Java gurus behind the scenes.

Switching to the other extreme, the view is the part of the application which the user sees and interfaces with. It’s temporary, it’s a facade and while it gives the user a way to interact with the interesting data in the model, it’s really just the superficial, friendly front end to that hard information. Most modern internet applications actually consist of a number of views — these could consist of big web interfaces for desktops, smaller web interfaces for mobile devices, or even dedicated mobile apps. All of these views need to communicate with the back end model.

The controller is the code that mediates between the various views and the model. The controller will be a piece of code that typically runs on the end device itself, although it is also possible for it to be a piece of middleware code sitting on a front end web server (this was generally the case with traditional web applications written in languages like PHP). Nowadays, due to speed considerations and the increasing power of Javascript frameworks like AngularJS and Backbone, the controller code is much more likely to reside on the end device, servicing the view just behind the scenes, and sending messages back and forth to the model.

Splitting up applications cleanly into Model-View-Controller architecture allows developers to enjoy what is called the “separation of concerns” — that is, 1) splitting the device-specific visuals and user interactions into various views (so the CSS and light display-oriented Javascript goes here), 2) splitting the user-interface logic and model-communication logic into various controllers (for web apps, this is heavier Javascript that handles basic data integrity and manages more complex aspects of the view’s current state) and 3) splitting the heavy-duty business logic and hard data into the model. This separation of concerns lets big teams focus on specific aspects of appliation development, and makes it easier to create scalable web apps where different parts of the system can be handled by specialists.

Next post I’ll cover the basics of how AngularJS lets us do MVC. We’ll start with some simple applications where the entire MVC architecture resides inside the app itself. In more advanced lessons, we’ll start to look at how to break out the model into external systems (such as through a REST api) so that we can develop full professional-grade systems.

AngularJS Big Concepts

Let’s take a step back and define our goal clearly: how to develop most efficiently a core skillset in AngularJS.

To get to this point, we’ll focus on the big concepts that an AngularJS coder needs to understand, and subsequent posts will address these in detail.

1. Understand Angular’s approach to the Model-View-Controller (MVC) programming paradigm

2. Implement the basic nuts-and-bolts of Angular: views, models, scope, two-way databinding, and controllers. Our hands-on how-to guide.

3. Routing – how to use Angular’s page routing system to implement single-page-applications that are the new popular approach to modern Javascript/AJAX style development

4. Directives – how Angular allows us to create special active extensions to HTML

5. CSS integration and creating polished interfaces

Understanding these concepts will win you basic competency in Angular, and pave the way for intermediate and advanced work later.

AngularJS Routing

One of the most important design patterns in web-based MVC systems like AngularJS is page routing. What is “page routing” in a nutshell?

Let’s take a look… one of the interesting capabilities of web-based MVC systems is the ability to swap in portions of a page without making a full page-load request, as happens with traditional html coding. Instead, some kind of small call is made to the server for a snippet of code that is swapped in somewhere in the view (the view in this case being the browser screen or some part of it).

Angular accomplishes this using the $routeProvider service. We wire this up by executing the following steps in this somewhat simple example that we’ll build on in future tutorials.

1. set up your application to use a specific module, with a name of your choice. This is done using the ng-app directive. Let choose the name “myApp” for our module — you could stick this snippet in your main index.html file:

<div ng-app="myApp">
    <div ng-view></div>

The ng-view directive tells Angular exactly where the html snippet will be displayed.

2. Next we define the module using the angular.module construct as follows… make sure this code is referenced as a javascript file.

angular.module('myApp', [])
    .config(function ($routeProvider) {
        .when('/', {template: '<div>This is the default div</div>'})
        .when('/todolist', {templateURL: '/partials/todolist.html'})

You can either insert template code directly as using the template property as with the first .when chain for the $routeProvider, or you can reference an html file using the templateURL property, as we do in the second example that links to the /partials/todolist.html file.

3. Finally let’s create some links. Let’s use the ng-href directive to let Angular know to replace these links with Angular-friendly hashtagged URLs. Angular uses hashtags to enable in-page switching of views. Insert this code in your index.html page right after your ng-view div tag.

<a ng-href src="/">This is our main page</a>
<a hg-href src="/todolist">This is our todolist page link</a>

…And that’s it for this simple example. Refresh your index.html page and you should now have a very basic working Angular router. We’ll build on this example in future installments.

Angular example

Let’s try some baby AngularJS — our first Angular tutorial. This is to see a “Hello World”-level example at work before we start learning the big picture. Because we likes the instant gratification, precious.

Briefly: AngularJS uses a Model-View-Controller programming concept. This involves separating the:

— Model (the data objects represented in your application), from the

— View (all the stuff the user sees — for example, all the differently tweaked screens and subscreens in Android vs iOS vs desktop browser versions of Chrome/Firefox/IE/Safari, etc), from the

— Controller (the glue code that manages the Model and connects it with the various Views).

That said, a minimally interesting “Hello World” example might look like this:

<html ng-app>   <!-- ng-app is a built-in Angular "directive"
                     which defines the Angular app boundary; 
                     in this case, from the starting <html> 
                     tag to the closing </html> tag -->

    <script src="">  
        <!-- load the angular javascript code -->
    </script> <!-- and close the script tag! -->
    <p ng-init=" name='World' ">Hello {{name}}!</p>
       <!-- here ng-init is a convenient "directive" which Angular
            provides to let you run code prior to execution of the
            main Angular template. In this case, we simply initialize
            the variable "name" with the value "World". According to 
            the Angular developers, this is a shortcut for toy/test
            applications. We'll use it for the moment and get a bit
            more professional shortly.

Now run this code in your browser, and you’ll get a nice, simple “Hello World!”

What happened here? We began with bootstrapping the AngularJS system — first we got the ball rolling by loading in AngularJS using the script tag. When that executed, it basically reads through the entire page starting at the top of the DOM (the Document Object Model — basically the html and css elements comprising the page) and pseudo-compiled according to the AngularJS system (a very loose use of terminology indeed, but enough for now). The “ng-app” directive embedded into the tag gave AngularJS the boundary of the code. And we initialized the Model (meaning the AngularJS model, not the DOM model) by assigning the variable “name” the value “World.” And finally, using the double-curly brackets (yet another AngularJS “directive”) around the variable “name”:

{{ name }}

we told AngularJS to look into the Model and substitute the value of the variable “name” in that spot.

The end result — our little Hello World!

Next… we’ll do this whole thing in a less toy-like fasion and build a more formal Model.

Why AngularJS? What’s the use case?

AngularJS is a hot new front-end MVC Javascript framework.

Basically that means: it’s a popular system to rapidly develop powerful, responsive web apps that end-users interact with.

Advantages: it’s meant to streamline the most common type of interactive development. So in theory it should save web developers time to develop apps where the main focus is manipulating data stored in a back-end database. These applications are often called CRUD applications, which stands for create/read/update/delete. The CRUD operations are the bread and butter operations made against databases to input, retrieve, change and remove information (i.e. create, read, update, and delete data).

Contrast with: jQuery, the most popular Javascript framework. jQuery’s “sweet spot” is very fine-grained manipulation of the web page — element by element, object by object — where elements and objects are things like text fields, form fields, images, videos, and clickable controls. jQuery gives developers great power over appearances and on-screen widgets of all sorts — moving them, animating them, hiding them. This fine-grained control over widgets comes from jQuery’s focus on manipulating the DOM (“Document Object Model”) which describes every singles little widget on the web page. AngularJS, by contrast, does not streamline those operations as efficiently, but focuses on tasks like handling updates to data (like when a user types something in a form field) and sending those updates to a back-end database (for permanent storage) as efficiently as possible. Those kind of operations are somewhat tedious to control through jQuery. AngularJS also makes it easy to filter and sort lists of objects (say, lists of people or products) displayed on a page with a minimum of hassle; with jQuery, that would be a more programming-intensive operation.

In short, AngularJS is focused on maintaining data models for objects, and how they are viewed on the front end. jQuery is focused on precise, atomic control of the page. Different philosophies and strengths.

One nice thing – you can combine AngularJS and jQuery to combine the strengths of both.

Welcome to AngularJS Tutorial at

Hey folks – thrilled you could visit. My goal with this site is to provide comprehensive information on AngularJS. I found there is a need for more diverse introductory materials to this interesting, powerful MVC (model-view-controller) Javascript framework, and hope to make this site an interesting resource for this wishing to learn more. It’s meant to provide a more comprehensive — and dare we say, gentler — introduction than you’ll find on Feel free to comment, contribute and communicate as this site grows.