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 http://www.angularjstutorial.com

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>
</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) {
        $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.

How to Handle the Flaky Console in Internet Explorer

Internet Explorer is a marvelous browser on many levels. One of these levels, somewhere near the middle of Dante’s circles of Hell, is that it provides developers many opportunities for extra work hours in order to develop work-arounds and fixes for its various deficiencies.

One of the limitations of IE is that the console, which we use for javascript debugging, either does not exist in some older versions (like 6, 7) or is unreliably existant (depending on whether the console is actually open) in newer versions. In Chrome, Firefox and Safari, we don’t need to worry about its basic non-existence. However, the code below even enables certain console refinements for these browsers because it fills in a dummy console where certain console logging warning levels may not exist.

This nifty code comes courtesy of Peter Tseng from the page http://stackoverflow.com/questions/3326650/console-is-undefined-error-for-internet-explorer to handle this mess. I’ll use the console in the code for basic debugging and quite frequently to see how often Angular fires up certain functions by itself as part of its model-managing event loop.

The code inside the consoleLog.js file is:

/*
monir's notes... added 12-Jun-2013
Console log fixer javascript. Protects against IE missing console issues. Refines other browsers.
from Peter Tseng's post on http://stackoverflow.com/questions/3326650/console-is-undefined-error-for-internet-explorer
*/
/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 */
(function() {
  if (!window.console) {
    window.console = {};
  }
  // union of Chrome, FF, IE, and Safari console methods
  var m = [
    "log", "info", "warn", "error", "debug", "trace", "dir", "group",
    "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
    "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
  ];
  // define undefined methods as noops to prevent errors
  for (var i = 0; i < m.length; i++) {
    if (!window.console[m[i]]) {
      window.console[m[i]] = function() {};
    }    
  } 
})();

Angular tutorial – todo list breakdown

AngularJS’s main website, Angularjs.org, has a to-do list example on the first page. It’s a nifty introduction to Angular with examples of “data-binding,” one of the key Angular concepts (other goodies like routers and modules to come in later posts). Here I’ll provide an breakdown of how it is put together. Please note – this analysis follows more along the line of the video they provide for the to-do list example, which is just slightly different.

The code consists of two core files (index.html and controllers.js), along with all the supporting javascript files for console logging, Angular, jQuery, underscore.js and a bit of CSS provided by the Bootstrap UI library.

Here is the index.html code I used:

<html ng-app>
	<head>
		<script type="text/javascript" src="consoleLog.js"></script>
		<script type="text/javascript" src="underscore-min.js"></script>
		<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
		<script type="text/javascript" src="angular.min.js"></script>
		<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
		<link rel="stylesheet" href="bootstrap/css/bootstrap.css">

		<script type="text/javascript" src="controllers.js"></script>
 	</head>

	<body ng-controller="todoController">
		Total todos: {{returnTotalTodos()}} 
		<ul class="unstyled">
			<li>testing</li>
			<li ng-repeat="todo in todos"><input type="checkbox" ng-model="todo.done" ng-click="handleTodoCheck()">{{todo.todoItem}}</li>
		</ul>

		<input type="text" ng-model="newTodoText" ng-model-instant ><button ng-click="addNewTodo()"><i class="icon-plus"></i>add one</button> {{newTodoText}}

		<div>
			<button ng-click="clearFinishedTodos()">Clear Finished Todos</button>
		</div>

	</body>

</html>

Let’s break that down a bit… first the beginning bits.

<html ng-app>
	<head>
		<script type="text/javascript" src="consoleLog.js"></script>
		<script type="text/javascript" src="underscore-min.js"></script>
		<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
		<script type="text/javascript" src="angular.min.js"></script>
		<script type="text/javascript" src="controllers.js"></script>
		<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
		<link rel="stylesheet" href="bootstrap/css/bootstrap.css">

		<!-- we got 5 lines of CSS in this tiny example app. So I'm inlining it! -->
		<style> 
		.done-true {
  			text-decoration: line-through;
  			color: grey;
		}
		</style>
 	</head>

We first activated Angular across the app using the “ng-app” directive inside the html tag. This wakes up Angular and makes it pay attention to everything between the opening and closing tags. Without that, no Angular.

Next we load up our javascript files. The first line loads up consoleLog.js which gives me a snippet of special console logger code I use on various projects. The reason why I initialize the console this way is because Internet Explorer handles the console.log function inconsistently depending on the IE version and other factors, so I throw in some boilerplate. I have a page where I describe how to handle the flaky console log in Internet Explorer.

Next I load up all the Javascript libraries including the most recent versions of underscore.js, jQuery, Angular and Bootstrap. I follow up by loading the controller file for this MVC (Model-View-Controller) app, which along with the index.html is the second custom-written file. Finally, I inline the 5 lines of custom CSS code we are going to use. Now some people object to inlining any CSS code; for this sake of this tiny demo app, and to avoid creating a tiny CSS file to download, I’ve chosen a simpler route. In a full professional application with more complex CSS, you should create separate CSS files.

After that follows the meat of the index.html:

	<body ng-controller="todoController">
		Total todos: {{returnTotalTodos()}} 
		<ul class="unstyled">
			<li ng-repeat="todo in todos"><input type="checkbox" ng-model="todo.done">
                          <span class="done-{{todo.done}}">{{todo.todoItem}}</span>
                        </li>
		</ul>

		<input type="text" ng-model="newTodoText" ng-model-instant ><button ng-click="addNewTodo()"><i class="icon-plus"></i>add one</button> {{newTodoText}}

		<div>
			<button ng-click="clearFinishedTodos()">Clear Finished Todos</button>
		</div>

	</body>

</html>

What’s going on here:
1. inside the body tag, we use the ng-controller directive to specify which controller code will be in charge (until the /body tag). Remember: the controller code is the Angularized code necessary to mediate between the Model and the View in our MVC (Model-View-Controller) app. Microtutorial: in an MVC app, the Model is the chunk of code/data that represents the “real world” objects in your app; the View is the visual stuff you see on screen that lets you interact with some representation of the Model (which might adapt responsively between a tiny mobile screen versus a big desktop screen); and the Controller is the glue code that separates and sets up communication between the Model and View, giving you the ability to re-use the Model with multiple View configurations (super important in a multi-device world where the Views are going to vary considerably depending on which device a user uses to access your app).

2. A very funny looking, non-HTML {{returnTotalTodos()}} references a function within our controller code that will update automagically to let us know the total count of todo list items. We’ll get to it soon!

3. We create a list using ul and li elements… The li elements are repeated for each todo item we have. We do this with the ng-repeat directive, our great cycling directive, which we’ll use to loop through the todos Model array defined in our controller code.

Let’s take a quick preview of the actual todos array (a starter todo list we use for the sake of example) defined in the controller. Don’t worry about the “$scope” business for now. We’ll see more of this later. For now — it’s just a basic Javascript object, with a todoItem field containing the text of each specific todo item, and a done field describing it’s status as complete (true) or incomplete (false).

	$scope.todos = [
		{todoItem: 'walk the dog', done: false},
		{todoItem: 'feed the cat', done: false}
	];

Back in our index.html file, the ng-repeat directive works as follows: when we specify

ng-repeat="todo in todos"

… Angular will find the “todos” array in our controller (it knows which controller to reference because we are within the body tag where it was first specified) and will loop through it object-by-object and will successively assign each object to the todo variable as it cycles through the loop. So what will happen here is that the li tag will be produced once for every object in the todo list, and each time we loop through li tags, we’ll have a different todo object to use for our data.

The ng-model=”todo.done” sets up a two-way data binding between the view and the model for this todo item. Simply using the ng-model directive, we create an automagic connection between the checkbox state (true/false) and the value of the done field (a mirrored true/false). This data-binding is one of the great benefits of Angular versus a regular framework like jQuery: we can save ourselves a lot of work, and make our code significantly simpler to follow, because we don’t have to directly manipulate the DOM (Document Object Model — the abstract page structure described by the HTML) in order to connect events in the View (e.g. clicking the checkbox) with the corresponding value of a data field in the Model (e.g. the value of the done field for this particular todo item). We did not even have to set up a click-event handler for this particular case — I did mention it was automagic, right?

Let’s add a field and button for new todo items:

<input type="text" ng-model="newTodoText" ng-model-instant ><button ng-click="addNewTodo()"><i class="icon-plus"></i>add one</button>

The ng-model=”newTodoText” directive here creates a two-way binding between the value of the text input, and the newTodoText model variable “inside” the scope of todoController controller (you remember — the one we referenced in the body tag). The ng-model-instant directive ensures it is updated in real time. In the “add one” button, we use the ng-click directive to bind the click event with the addNewTodo() function defined in the controller. The and tags add a bit of CSS prettiness — they give us a nice plus icon courtesy of the icon-plus class defined by Bootstrap. The addNewTodo() will, as you may have guessed, execute the logic necessary to add this newly inputted todo item to the array of todos.

Finally we throw in a button to delete the completed todos from our list. This will trigger a function in our controller to do the actual cleanup of the todo array — when that executes, we’ll see the results instantly reflected in our view in the form of a cleaned up list. A simple ng-click directive ties the button together with the corresponding function in the controller.

		<div>
			<button ng-click="clearFinishedTodos()">Clear Finished Todos</button>
		</div>

OK. That’s the index.html file. The controllers.js file contains our controller code and serves as the brain of the application. Here’s the source for the controller.js file and we’ll go through it bit by bit:


function todoController($scope) {

	$scope.todos = [
		{todoItem: 'walk the dog', done: false},
		{todoItem: 'feed the cat', done: false}
	];
    
    $scope.returnTotalTodos = function () {
    	console.log ('returnTotalTodos executes');
    	return $scope.todos.length;
    }


    $scope.addNewTodo = function () {
    	 console.log ('addNewTodo executes');
    	         var nothing = $scope.todos.length;
    	         var nothing2  = nothing;
    	if ($scope.newTodoText.length){
    		$scope.todos.push ( {todoItem: $scope.newTodoText , done: false});
    		$scope.newTodoText = '';
    	}

   
    }

    $scope.clearFinishedTodos = function () {
    	console.log ('clearFinishedTodos executes');
    	$scope.todos = _.filter($scope.todos, function (todo) {return !todo.done})
    }

}

First we start with the line

function todoController($scope) {

Looks simple. Is simple. Yet deceivingly powerful. The todoController is the name of our controller referenced from the body tag in the html. It’s got to be the same name — that’s how Angular associates the ng-controller we specified with the actual controller code function. And the $scope reference passed in is super-important. This is data structure passed in by Angular which sets the entire stage for dependency injection. Dependency Injection (DI) is one of the core concepts of Angular JS’s approach to MVC. What DI does is pass in to the controller code the “glue” data structure that sets the context and scope for all variables and functions inside the controller. Angular is a very clean system — it allows us to run multiple Angular apps on the same page, all potentially with different controllers. And while there are many levels to DI, the most direct and straightforward explanation here is that we pass in a data structure (called $scope) which is going to hold all other model variables and controller functions within it. Angular has NO global scope — it uses dependency injection to allow us to operate clean namespaces so we can use all our other libraries (jQuery, Yahoo YUI, etc) without fear of namespace overlap (and the corresponding chaos that would ensue).

All our variables and functions inside the controller will be included within $scope, as we shall see. And since Angular monitors $scope for us later, this dependency injection process enables the automagic processes necessary for two-way data binding between Views and Models.

Again – there is more to dependency injection both in general and as it applies to Angular – but that’s a sufficient basis for understanding for now.

This tutorial will be continued in a few days… Thanks for tuning in!

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 -->

  <head>
    <script src="http://code.angularjs.org/1.0.5/angular.min.js">  
        <!-- load the angular javascript code -->
    </script> <!-- and close the script tag! -->
  </head>
  <body>
    <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.
       -->
   
  </body>
</html>

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 www.angularjstutorial.com

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 http://angularjs.org. Feel free to comment, contribute and communicate as this site grows.