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
angular.module('myApp',['ngRoute'])
// end angular module (app) definition

// start config block with routing definition
 .config(function($routeProvider) {
   $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) {
   $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.';
      }
    })
    .otherwise({
       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.

index.html

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js"></script>
  <script src="http://code.angularjs.org/1.3.0/angular-route.js"></script>
  <script src="script.js"></script>
</head>
<body ng-app="myApp">
  <div ng-view></div>
</body>
</html>

script.js

// 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)
angular.module('myApp',['ngRoute'])
 .config(function($routeProvider) {
   $routeProvider
   .when('/', {
    templateUrl: 'homeView.html',
    controller: 'myAppController'
    });
 })
 .controller('myAppController', function($scope) {
  $scope.user = {};
  $scope.user.firstName = 'Joe';
 });

homeView.html

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 $scope.xyz 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 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.

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.