Day 2: AngularJS--Getting My Head Around AngularJS

Yesterday I kicked off a challenge where in I will learn a new technology every day for a month. In the first post of this month long series, I talked about Bower -- package manager for client side assets. You can read the blog here.  You can read the reddit discussion here.

Today I am going to learn basics of AngularJS and hopefully will be creating a very simple application using it.  This blog is live feed of my AngularJS learning experience. I will be using bower as well in this blog post. I know I can't cover AngularJS in one day so I will be spending multiple days on it but will cover different topics within AngularJS.

AngularJS

What is AngularJS?

  1. Extending HTML to add dynamic nature so that we can build modern web applications with ease
  2. Use the way you want.
  3. Brings you back to HTML
  4. Declarative Approach
  5. Simplicity
  6. Eliminates DOM manipulation by two way data binding. When ever a model changes view gets updated and vice-versa
  7. You can use it to build Single Page Web applications. There are lot of challenges when you build SPA applications like Routing, Ajax calls, data binding, caching, history, and DOM manipulation.

Main components of AngularJS are

  1. Controller : Code behind the view.
  2. Scope : Contains model data. Glues controller and view.
  3. Module : To define new services or use existing services , directives , filters , and so on. Modules can depend on another modules.
  4. Directive : Allows you to extend HTML by defining your own project specific HTML directives. They teach HTML new tricks.

AngularJS from 30000 feet above

Angular High Level

Why should I care?

For me there are two main reasons why I care about learning AngularJS:

  1. Backed by Google and enjoys a large community of developers
  2. Full Stack framework : This means I don't have to rely on a million other scripts without confidence they will integrate nicely together

Prerequisite

We will use Bower to install AngularJS for our sample application. If you don't already have bower installed then follow my previous blog post to learn about bower.

Installing AngularJS

Create a new directory called bookshop at any convenient location on your file system and the run the following command to install AngularJS and twitter bootstrap:

$ bower install angular
$ bower install bootstrap

This will create a folder called bower_components in the bookshop directory where you will have all the installed components.

Let's Use AngularJS

Now that we have AngularJS installed, lets create a html file called index.html which will be our AngularJS based online bookshop application.

<!doctype html>
<html>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container">
          <h2>Your Online Bookshop</h2>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>

If you open this in your web browser you will see "Your Online Bookshop" being rendered. This is not all that interesting so lets add some AngularJS magic:

<!doctype html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-init="books=['Effective Java','Year without Pants','Confessions of public speaker','JavaScript Good Parts']">
        <h2>Your Online Bookshop</h2>
        <ul class="unstyled">
            <li ng-repeat="book in books">
                {{book}}
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>

In the code shown above there are few notable things :

  1. In our html tag we have defined ng-app. This initialize AngularJS app and tells AngularJS to be active in this portion. So , in our application it is active for the full html document.
  2. The second angular directive that we have used is ng-init. This initializes an array of books array which we can use in our application.
  3. The last interesting part is the ng-repeat directive which is used to iterate over all the elements in a collection. Angular would add li elements for each elements. So, if we open this in web browser we will see four books in a list.

The above was using data in the form of String array but you can store objects as well shown below.

<!doctype html>
<html ng-app>
<head>
        <title>Bookshop - Your Online Bookshop</title>
        <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
        <div class="container" ng-init="books=[{'name': 'Effective Java', 'author':'Joshua Bloch'},{'name': 'Year without Pants', 'author':'Scott Berkun'},{ 'name':'Confessions of public speaker','author':'Scott Berkun'},{'name':'JavaScript Good Parts','author':'Douglas Crockford'}]">
                <h2>Your Online Bookshop</h2>
                <ul class="unstyled">
                        <li ng-repeat="book in books">
                                <span>{{book.name}} written by {{book.author}}</span>
                        </li>
                </ul>
        </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>

In the code shown above, we create an array of books object where each book object has name and author. Finally, we list both the author name and the book name in the list.

Using Filters

Angular provides filters which helps format the data. You can use a filter for formatting dates, currency, lowercase characters, uppercase characters, orderBy, and search based filtering. Below is an example how you can make use filters to uppercase Author name and orderby book name:

<!doctype html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-init="books=[{'name': 'Effective Java', 'author':'Joshua Bloch'},{'name': 'Year without Pants', 'author':'Scott Berkun'},{ 'name':'Confessions of public speaker','author':'Scott Berkun'},{'name':'JavaScript Good Parts','author':'Douglas Crockford'}]">
 
        <h2>Your Online Bookshop</h2>
        <ul class="unstyled">
 
            <li ng-repeat="book in books | orderBy :'name'">
                <span>{{book.name}} written by {{book.author | uppercase}}</span>
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>

As you can see above we used a orderBy filter in the ng-repeat directive and we used an uppercase filter while displaying author name.

To add a search filter add a text box for search input and then use a filter to limit your results as shown below.

<!doctype html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-init="books=[{'name': 'Effective Java', 'author':'Joshua Bloch'},{'name': 'Year without Pants', 'author':'Scott Berkun'},{ 'name':'Confessions of public speaker','author':'Scott Berkun'},{'name':'JavaScript Good Parts','author':'Douglas Crockford'}]">
 
        <h2>Your Online Bookshop</h2>
               <input type="search" ng-model="criteria">
        <ul class="unstyled">
 
            <li ng-repeat="book in books | filter:criteria | orderBy :'name'">
                <span>{{book.name}} written by {{book.author | uppercase}}</span>
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>

Using Controllers

Controllers are one of the main components of AngularJS. They are the code that will power and provide data to your views. In our example we can move the array test data initialization code to a controller. We will create a new JavaScript file called app.js which will house all our application specific JavaScript code.

function BookCtrl($scope){
        $scope.books = [
                {'name': 'Effective Java', 'author':'Joshua Bloch'},
                {'name': 'Year without Pants', 'author':'Scott Berkun'},
                { 'name':'Confessions of public speaker','author':'Scott Berkun'},
                {'name':'JavaScript Good Parts','author':'Douglas Crockford'}
        ]
}

The $scope is the glue between the controller and view and will get injected into our BookCtrl. Now we add our books array to the $scope object which will be visible to our view.

And we will change our index.html to use BookCtrl as shown below:

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-controller="BookCtrl">
        <h2>Your Online Bookshop</h2>
        <input type="search" ng-model="criteria">
        <ul class="unstyled">
            <li ng-repeat="book in books | filter:criteria | orderBy :'name'">
                <span>{{book.name}} written by {{book.author | uppercase}}</span>
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

Thats it for today's blog. I have only touched tip of iceberg. I will spending many days learning features of AngularJS. It is an amazing and powerful library.

What's Next

This is a nice tutorial, I wish if you can continue AngularJS tutorial., Thanks