LxD Series: $scope and Controllers

08-Feb-2015

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:

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.