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:


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:


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

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.


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:

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?


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