Monthly Archives: March 2014

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.