Learning AngularJS Simplified - Part Two

Introduction

My previous lab1 series on AngularJS was the first article in a series where you saw what AngularJS is, and how we can set up our application to start developing web applications.

Two way data binding

This is a very important feature of AngularJS. It helps to make view and model in sync always. AngularJS works in the model view controller pattern.


Any changes to the view are immediately reflected in the model, and any changes in the model are propagated to the view.
Two-way bindings in AngularJS are created with the ng-model directive.

Students.js

  1. /step1  
  2. /// <reference path="angular.min.js" />  
  3.   
  4. var studentsApp = angular.  
  5. module("studentsModule", []).  
  6. controller("studentController", function ($scope) {  
  7.   
  8.    $scope.message = "Hi There Students Controller!!!!";  
  9. });  
HTML Code
  1. <!DOCTYPE html>  
  2. <html ng-app="studentsModule">  
  3. <head>  
  4.     <title></title>  
  5.     <h2>Students Details</h2>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/angular.min.js"></script>  
  8.     <script src="Scripts/StudentsJS.js"></script>  
  9. </head>  
  10. <body ng-controller="studentController">   
  11.   <div >  
  12.         <input ng-model="message" />  
  13.         <br />  
  14.         {{message}}  
  15.      
  16.  </div>  
  17. </body>  
  18. </html>  
Result



Above message is the model which has got bound using ng-model directive which makes the model get updated once view is changed. This is a very nice feature of angular which makes it a good binding framework to keep the view and model in sync.



Here you can see the change in input is getting updated to the expression in real time .

Scope and rootScope in AngularJS

Scope is the linking between application controller and the view. Basically it’s nothing but an object which refers to application model.

In controllers, model data is accessed via $scope object.



Students.js
  1. var studentsApp = angular.  
  2. module("studentsModule", [])  
  3.     .  
  4. controller("studentController", function($scope)  
  5. {  
  6.     var studentDetails = {  
  7.         studentName: "Abhishek Singh",  
  8.         Age: 16,  
  9.         Standard: "10th"  
  10.     };  
  11.     $scope.studentData = studentDetails;  
  12.     $scope.message = "Hello from Students Controller!!!!";  
  13. });  
View Code
  1. <!DOCTYPE html>  
  2. <html ng-app="studentsModule">  
  3. <head>  
  4.     <title></title>  
  5.     <h2>Students Details</h2>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/angular.min.js"></script>  
  8.     <script src="Scripts/StudentsJS.js"></script>  
  9. </head>  
  10. <body  ng-controller="studentController">  
  11.   
  12.     <div >  
  13.        First Message:  {{message}}  
  14.     </div>  
  15.     <br />  
  16.     <div >  
  17.         Student Name :  {{studentData.studentName}}  
  18.         <br />  
  19.         Age:{{ studentData.Age}}  
  20.         <br />  
  21.         Standard:{{studentData.Standard}}  
  22.     </div>  
  23.     <br />  
  24.     <div>  
  25.         {{Name}}  
  26.   
  27.         {{StudentName}}  
  28.     </div>  
  29.   
  30. </body>  
  31. </html>  
This example is from the previous Demo Example --  here we can see $scope is passed as first argument to controller during its constructor definition.

In StudentData property of the $scope,  detractive studentdetails data is attached,  which will be evaluated by the expression on view page where the studentController is attached to HTML DOM element.

By using scope,  model data will be passed from controller to view.

AngularJS creates and injects a different $scope object to each controller in an application. So, the data and methods attached to $scope inside one controller cannot be accessed in another controller.

rootScope

Scope is controller specific. If we define nested controllers then child controller will inherit the scope of its parent controller.

The properties and methods attached to $rootScope will be available to all the controllers. Each Angular application has exactly one rootscope but may have several child scopes.

Student.js
  1. /// <reference path="angular.min.js" />  
  2. var studentsApp = angular.module("studentsModule", []);  
  3. studentsApp.controller("studentController", function ($scope, $rootScope) {  
  4.     $scope.Message1 = "This is from studentsController";  
  5.     $rootScope.UniversalMseeage = "This is Global Massage"  
  6. });  
  7.   
  8. studentsApp.controller("classController", function ($scope) {  
  9.     $scope.Message2 = "This is from classController";  
  10.   
  11. });  
View code
  1. <!DOCTYPE html>  
  2. <html ng-app="studentsModule">  
  3. <head>  
  4.     <title></title>  
  5.     <h2>Students Details</h2>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/angular.min.js"></script>  
  8.     <script src="Scripts/StudentsJS.js"></script>  
  9. </head>  
  10. <body >  
  11.     <div ng-controller="studentController">  
  12.     {{UniversalMseeage}}  
  13.     <br />  
  14.         {{Message1}}  
  15.     </div>  
  16.     <br />  
  17.     <div ng-controller="classController">  
  18.         {{UniversalMseeage}}  
  19.         <br />  
  20.         {{Message2}}  
  21.     </div>  
  22. </body>  
  23. </html>  
Result in browser



Basically two controllers, studentController and classController scope object, have limited access which is the HTML element where that particular controller is bound using ng-controller or its child elements.

rooptScope is the parent of all scopes and it will be accessible to all the HTML elements.

Service in AngularJS

Service in angular is nothing but a JavaScript function which is created to perform a certain task. It will be used to share the functionality with different controllers by using dependency injection.

Dependency injection.  Okay are you confused again?

I'm just briefing you about dependency injection butI'm  diving deep.

Dependency injection is a very interesting topic to learn.

AngularJS Built in  Service


AngularJS has many Built in services to support certain functionalities.

AngularJS built-in services starts with $

A few are below,

$http,
$route,
$window,
$location


AngularJS services are lazy,  instantiated,  and singleton in nature.

The meaning of the above line is Service is instantiated by AngularJS when an application component depends on it and all the components share the same instance of a service.

Most commonly used angular service is $http

$http

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

User Created Service

It can be done using two methods.

Factory method


  1. studentsApp.factory(“TestSerive”)  
.Factory ()
  1. studentsApp.factory("studentfactory", function () {  
  2.       
  3.  return {  
  4.         displayName: function (name) {  
  5.             return "Hello from Factory : " + name;  
  6.         }  
  7.     };  
  8.   
  9. });  
Service Method


  1. studentsApp.service("studentService", function () {  
  2.        this.displayName = function (name) {  
  3.            return "Hello" + name ;  
  4.        };  
  5.    });  
  6.   
  7.    Name: studentService  
  8.    Callback: javascript fucntion  
  9.   
  10. app.controller('AppController', function ($scope,MyService) {  
  11.   MyService.sayHello(); // logs 'hello'  
  12. });  
Service method,

Stduents.js
  1. //step1  
  2. /// <reference path="angular.min.js" />  
  3. var studentsApp = angular.  
  4. module("studentsModule", [])  
  5.     .  
  6. controller("studentController", function($scope, studentService, studentfactory)  
  7. {  
  8.     var studentDetails = {  
  9.         studentName: "Abhishek Singh",  
  10.         Age: 16,  
  11.         Standard: "10th"  
  12.     };  
  13.     $scope.studentData = studentDetails;  
  14.     $scope.message = "Hello from Students Controller!!!!";  
  15.     $scope.Name = studentService.displayName("Abhishek Singh");  
  16.     $scope.StudentName = studentfactory.displayName("David");  
  17. });  
  18. studentsApp.factory("studentfactory", function()  
  19. {  
  20.     return {  
  21.         displayName: function(name)  
  22.         {  
  23.             return "Hello from Factory Method : " + name;  
  24.         }  
  25.     });  
  26.     studentsApp.service("studentService", function()  
  27.     {  
  28.         this.displayName = function(name)  
  29.         {  
  30.             return "Hello from Service Method : " + name;  
  31.         };  
  32.     });  
  33. }  
HTML Code
  1. <!DOCTYPE html>  
  2. <html ng-app="studentsModule">  
  3. <head>  
  4.     <title></title>  
  5.     <h2>Students Details</h2>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/angular.min.js"></script>  
  8.     <script src="Scripts/StudentsJS.js"></script>  
  9. </head>  
  10. <body ng-controller="studentController">  
  11.      
  12.  <div >  
  13.        First Message:  {{message}}  
  14.     </div>  
  15.    <br />  
  16.     <div>  
  17.         {{Name}}  
  18.         <br>  
  19.         {{StudentName}}  
  20.     </div>  
  21. </body>  
  22. </html>  
Output



Difference between Factory and Service method

Services and Factories both are singletons and can be used to achieve the same functionality.

Factory
  • Factory is a function that returns an object explicitly. A factory is a simple function which allows you to add some logic before creating the object and also helps doing some configuration stuff or conditionally.
  • When the service instance requires complex creation logic.
  • When you need to work with an object, you could use the factory provider.

Service

  • When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.
  • Should be used for simple creation logic.

Resource References

You can read more for the directive using API references of the angular website.


Similar Articles