Learn AngularJS Hour 5: All about $scope object

In hour 1 , we learnt to get started with AngularJS.

In hour 2 , we learnt about AngularJS Template.

In hour 3 , we learnt about two way bindings and filter.

On hour 4 , we learnt about $http service and making HTTP operations.

In 5th hours of series, we will learn about $scope in Angular. $scope is an object which connects View and Controller together.

 

image

To understand $scope better let us start with first angular app we wrote,

image

Above program ran and due to $rootScope of angular. When you don’t provide any $scope explicitly, angular works with $rootScope. To understand $rootScope better let us understand below diagram,

image

We have added attribute name in $rootScope under the main function. Main function can be considered as main method of angular app. Since attribute is added to $rootScope, it can be accessed anywhere on the view and we do not need controller to access this. Due to $rootScope hello world ng-model of textbox got rendered on the view with template {{name}}.

For complex application you will have to create explicit $scope. Consider we have a view as below,


<div ng-controller="authorController" >
        {{author.name}} is {{author.age}} old
    </div>

Here we have attach a controller object to div element of DOM in view. Now to make sure that author.name and author.age attribute is available on the view, we need to create explicit $scope. That can be created as below,


app.controller('authorController', function ($scope) {
    $scope.author = {
        name: "Dhananjay Kumar",
        age: 32
    };
});

Attribute author of authorController will be available to all child element of the div to which authorController is attached. For example consider below View, we are able to read value of author attribute in child div as well,

  <div ng-controller="authorController" >
        <div>
            I am in child div  <br/>
            {{author.name}} is {{author.age}} old
        </div>
    </div>

We can summarize few points about $scope as follows,

  • $scope ties view and controller together
  • $scope provides an execution context in which DOM element is bound
  • In context of MVC , $scope can be seen as model
  • View and model both have access of $scope
  • $scope holds data and functions from controller that should be displayed and get executed in view
  • $rootScope is top most scope in on DOM element with ng-app directive

In angular all the $scope are created with prototypal inheritance. All $scope has access to their parent scope. For above example $scope of authorController has access to $rootScope. On the view $scope of child controller can access attributes of parent controller. To understand it better, let us create two controllers. authorController is parent controller and childAuthorController is child controller. You can see in the child controller childAuthorController that author attribute of authorController


var app = angular.module('AuthorApp', []);

app.controller('authorController', function ($scope) {
    $scope.author = {
        name: "Dhananjay Kumar",
        age: 32
    };
});

app.controller('childAuthorController', function ($scope) {

    $scope.hello = function()
    {
        alert($scope.author.name);
    }
})


On the view we have two div, first div is attached to parent controller whereas second view is attached to child controller.


<div ng-controller="authorController" >
        <div ng-controller="childAuthorController">
            
            {{author.name}} is {{author.age}} old
            <button ng-click="hello()" class="button" >say Hello</button>
        </div>       
    </div>

You can see that we have access of parent controller attributes inside DOM element which is attached with child controller.

$scope work on prototypal inheritance in angular. Diagrammatically we can show that as follows,

image

This is the way $scope object works in angular. Even though it performs complex tasks like binding controller and view together at the end of the day it is simple JavaScript object. Having a good knowledge on $scope is big help in implementing complex angular applications. Happy coding.

Learn AngularJS Hour 4: service in AngularJS and making HTTP call using $http

In hour 1 of this series we learnt to get started with AngularJS.

In hour 2 of this series we learnt about AngularJS Template.

In hour 3 of this series we learnt about two way bindings and filter.

In this hour we will learn about,

  • · Using Services in Angular
  • · Calling remote service to load data

If you are following this hour series on AngularJS, you might have noticed that we are using local data for authors. Using Services in AngularJS, you can call a remote service. Here we are going to call a HTTP based (REST Service) service. You can use $http of AngularJS to call a remote service or to make a HTTP request.

image

So in controller we need to modify to make a call to the service. In below example service is returning JSON.

image

Let us see what is happening in above code,

  • $http service is making HTTP GET operation
  • Service is returning JSON data
  • $http service returns promise object having success method. In this method service response will be handled asynchronously.
  • In success method of promise object of $http service, Angular is assigning returned data to current scope and creating model named author
  • Parsing of returned data is done by angular.

As you might have noticed that to use a service we need to pass service as dependency in the constructor of Controller.

clip_image001

Dependency Injector of Angular provided services to controller. It works in three steps,

  1. Injector identifies $http as dependency of controller
  2. Injector checks whether instance of $http exist or not? if not creates new instance of $http
  3. Injector pass singleton instance to controller of service. In this case Angular dependency injector will check whether $http service singleton instance is passed to AuthorController or not?

image

So for your reference code from above discussion is given below. Module and Controller is created given below,


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

AuthorApp.controller('AuthorController',
                      function ($scope, $http)
{
   
    $http.get('http://localhost:21800/Service1.svc/GetAuthors')
        .success(function (data)
        {
                 $scope.authors = data;
        });
    
});


And View is as below,


<!DOCTYPE html>
<html ng-app="AuthorApp">
<head>
    <title>Angular Demo</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Author.js"></script>
</head>
<body ng-controller="AuthorController">

    Search: <input ng-model="searchtext">

    Sort:
    <select ng-model="sortorder">
        <option value="AuthorName">Name</option>
        <option value="age">Age</option>
    </select>

    <ul>
        <li ng-repeat="author in authors |
            filter:searchtext |
            orderBy:sortorder">
            {{author.AuthorName}}

       </li>
    </ul>
</body>
</html>


On the web page all the authors will be rendered as below,

image

We learnt how easy it is using Angular service to make a HTTP request. We also learnt about using Angular service like $http in application. Happy coding.