LxD Series: Implementing AngularJS templates and routers

Ok so we are going to implement templates and routers in AngularJS. Routers are going to help us to get unique URLs per page, or view while templates, as you know will help to provide theme of our app.

NgAddressBook

This is what we came up in my last post. What I am going to do to shift the markup of this listing in a separate file and come up with a layout. Therefore index.html will look like this:

<!doctype html>
<html ng-app="ngAddressBook">
<head>
    <title>Ng Addressbook</title>
    <link href="main.css" rel="stylesheet" media="screen" />
</head>
<body>
    <div ng-controller="ngAddressListController">
        <div id="container">
            <h1>Ng Address Book</h1>
            <div id="content" ng-view>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
    <script src = "angular-route.min.js"></script>
    <script src="main.js"> </script>
</body>
</html>

You should notice that I removed all the stuff from content div and add another directive, ng-view. Ng-view tells AngularJS that particular DIV will be used as a container of multiple views. Now I create a folder named views and a file in it with name list.html

<h3>There are <span id="count">{{getTotalContacts()}}</span> Contacts So far</h3>
<span><a href="#/add">Add</a></span>
<table>
    <tr id="h">
        <td>First Name</td>
        <td>Last Name</td>
        <td>Phone</td>
        <td>Email</td>
    </tr>
    <tr ng-repeat = "contact in contacts">
        <td><a href="#/details/{{contact.id}}">{{contact.first_name}}</a></td>
        <td>{{contact.last_name}}</td>
        <td>{{contact.Phone}}</td>
        <td>{{contact.Email}}</td>
    </tr>
</table>

Now this thing need to be accessed via URL and for that routers need to be defined. In main.js routers will be set like this:

var ngAddressBook = angular.module('ngAddressBook', ['ngRoute']);
ngAddressBook.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'views/list.html',
                controller: 'ngAddressListController'
            });
}]);

In above code main route has been set by configuring $routeProvider  which takes two parameters; first takes pattern of matched path, in our case it’s ‘/’ while second parameter takes an object having properties templateUrl and controller.

Basically, the code above tells AngularJS that when someone main URL(‘/’) it should execute the controller ngAddressListController and pass on the data from controller to template list.html. Result will be same as given on above screen. Let’s a couple of screens further in the app. One to add record and other to show details of individual record.

<form>
    <label>
        First Name
        <input type="text" id="first_name" value="" />
    </label>
    <label>
        Last Name
        <input type="text" id="first_name" value="" />
    </label>
    <label>
        Phone
        <input type="phone" id="phone" value="" />
    </label>
    <label>
        Email
        <input type="email" id="email" value="" />
    </label>
    <input type="submit" value="Add" />
</form>

 

<h2>Details of #{{id}}</h2>
<h2>To be done by You!! :-)</h2>

 

Javascript will now look like this:

var ngAddressBook = angular.module('ngAddressBook', ['ngRoute']);

ngAddressBook.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'views/list.html',
                controller: 'ngAddressListController'
            }).
            when('/add', {
                templateUrl: 'views/add.html',
                controller: 'ngAddressListController'
            }).
            when('/details/:id', {
                templateUrl: 'views/details.html',
                controller: 'ngAddressDetailsController'
            });
    }]);
// add a controller to it
ngAddressBook.controller('ngAddressListController', ['$scope', function ($scope)
    {
        $scope.contacts = [
            {id:1,first_name:'Jane', last_name:'Doe','Phone':'123-456789','Email':'jane@example.com'},
            {id:2,first_name:'Jhon', last_name:'Doe','Phone':'123-456789','Email':'jhon@example.com'}
        ];
        $scope.getTotalContacts = function () {
            return $scope.contacts.length;
        };
    }]);



ngAddressBook.controller('ngAddressDetailsController', ['$scope', '$routeParams',
    function($scope, $routeParams)
    {
        $scope.id = $routeParams;
        //alert($routeParams);
    }]);

I added two more routers; /add and /details:id . You should notice that I created a separate controller, ngAddressDetailsController in which I accessed queryString parameter by passing $routeParams which holds info of all parameters passed via when() method. In detail view you can access it by calling $scope object.

I have left the implementation of detail View. It should not be difficult if you follow what I mentioned in this post.

That’s all folks. Next post will be the last post in AngularJS series in which I will cover to $http object for AJAX purpose.

You can get the latest code of this post from Github.
As always, give your feedback and find mistakes in the posts to make them better.

 

Join with me and let’s learn together!

* indicates required