LxD Series: $scope and Controllers

I learnt a few basics of AngularJS here and here and now I am making a giant leap and implementing first screen of our Ng Addressbook which will look like this:

NgAddressBook

So let’s get into it. In this post we are going to discuss some important concept of Angular called Scope. A scope is a JS object that holds info of both data execution. In short $scope variable acts as both controller and model as it sits between them. You can learn further about scope here. When you don’t explicitly define a $scope, Angular uses $rootScope which is visible within code block where you initiated your angular App. In previous post we were able to access {{Name}} variable because $rootScope was defined.

Ok now our code is expanded a bit and also divided into multiple files. First check the html part:

 

<!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>
            <h3>There are <span id="count">{{getTotalContacts()}}</span> Contacts So far</h3>
            
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
    <script src="main.js"> </script>
</body>
</html>

A separate JS file now has been added which looks like this:

function ngAddressListController($scope)
{
    $scope.contacts = [
        {first_name:'Jane', last_name:'Doe'},
        {first_name:'Jhon', last_name:'Doe'}
    ];
   $scope.getTotalContacts = function () {
            return $scope.contacts.length;
        }; 
}

I will do it step by step.

<div ng-controller="ngAddressListController">  defined a controller having name ngAddressListController for this purpose ng-controller directive was used. Ok all seems good and now let’s run this code.

OOps! Blank page. I don’t think I did anything wrong. On Chrome console I found following error:

AngularJS error

I followed the link given in error which had following text:

Error: error:modulerr
Module Error

Which means that I have not defined an application module. Upon further investigation on Internet and asking on Stackoverflow I found that newer versions of AngularJS has killed the concept of defining controller globally. Let’s make changes in main.js.

 

angular.module('myApp', [])
// add a controller to it
    .controller('ngAddressListController', ['$scope', function ($scope)
    {
        $scope.contacts = [
            {first_name:'Jane', last_name:'Doe','Phone':'123-456789','Email':'jane@example.com'},
            {first_name:'Jhon', last_name:'Doe','Phone':'123-456789','Email':'jhon@example.com'}
        ];
        $scope.getTotalContacts = function () {
            return $scope.contacts.length;
        };
//    }]);

Here I defined an Angular Module, ngAddressBook which then adds a ‘method‘, controller with required parameters. Here I passed name of controller in first param and then $scope object with function to process it.

Since our application is a ContactBook, I add a contacts object with properties that will hold data. The method getTotalContacts() return count of obect Array

Now, I have to list down these records on my front page. The page will now 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>
            <h3>There are <span id="count">{{getTotalContacts()}}</span> Contacts So far</h3>
            <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>{{contact.first_name}}</td>
                    <td>{{contact.last_name}}</td>
                    <td>{{contact.Phone}}</td>
                    <td>{{contact.Email}}</td>
                </tr>
            </table>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
    <script src="main.js"> </script>
</body>
</html>

Here you see another directive, ng-repeat. ng-Repeat  is used for loop. So we re iterating contacts object and displaying our desired results. When you run it, it will show what we saw above. Simple, isn’t it?

NgAddressBook

I have also push this code on my github account so that you can download and play with it. Get the code from here.

As always, your comment, feedbacks and corrections are welcome.

Join with me and let’s learn together!

* indicates required