AngularJS Overview Series - Three

Introduction

Hello folks! Let's continue our journey of learning AngularJS. We have seen and discussed a few topics already!

In this article we will discuss a few concepts that are very essential to build an MVC project with Angular.

Think Let's see the topics we will be covering in this article:

  • Angular Model
  • Angular Scopes
  • Angular Services
  • Angular Http
  • Angular Dependency Injection
  • Angular Model

This as the name suggests binds the values to the model associated to an element. This shows a two-way binding, i.e. when the value supposed in the textbox changes, the value for the model also binds and changes. The attribute used is ng-model, the code would be like:

  1. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  2. <div>Name : <input type="text" />  
  3.     <h1>Welcome {{name}}</h1>   
  4. </div>  
  5.   
  6. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  7.   
  8. <div>Name : <input type="text" />  
  9.     <h1>Welcome {{name}}</h1>        
  10. </div>  
This will update the value of text entered inside the text box and gets displayed in real time.

Source

Interesting fact about the ng-model directive is that, the directive watches the model by reference not by value. It also provides validation to the particular field.

Angular Scopes

Angular scopes are the execution-context generated during the creation of a controller. We pass the scope object to the controller function. The scope is generally denoted as $scope. This is actually an object to which we add the properties to be accessed in the HTML page using the controller reference.

As the angular doc rightly says, it is actually the glue between the controller and the view. It comes with two referring API i.e. $watch (used to observe the model mutations) and $apply (used to propagate the changes done to the scope object property) Lets have a glance at the snippet:
  1. angular.module('scopeTest', []).controller('TestController', function($scope) {$scope.username = Suraj;});  
This is how the scope object is passed and initialized and assigned properties to be used inside the view.

Interesting Facts

Controller function in Angular is a constructor function. Now what is a constructor function?

A constructor function in simple terms is when the new keyword is used before a function.
  1. var constructorFunction = new Funciton(Parameters..);  
Thus every time a controller is instantiated it gets associated with a new Scope.

Angular Services

There are many built-in services provided by the Angular and also we can explicitly create our own service to have a loose coupling while using the Http Get Post services. These are actually singleton functions that are required to perform certain specified tasks. What singleton means is restricting the instantiation to a single object only.

As in MVC we follow Separation of concern, here also these services can be used to follow the loose coupling and binding.

Separation of concern

As we can see here the reuse of the services can also be followed here. This is done using the injection of dependency into the controller function. We will look into the dependency in the next points.

Lets see how we declare a service in Angular.
  1. var module = angular.module('TestApp', []);  
  2. module.service('TestService', function()  
  3. {  
  4.     this.users = ['Suraj''CsharpCorner''Angular'];  
  5. });  
Here comes another concept known as Factory, which also behaves as a service function only.
  1. var module = angular.module('TestApp', []);  
  2. module.factory('TestFactory', function()  
  3. {  
  4.     var testFactory = {};  
  5.     testFactory.users = ['Suraj''CsharpCorner''Angular'];  
  6.     return testFactory;  
  7. });  
The behavior is the same for both service and factory, but the difference is interesting. For the difference, take a closer look at the snippets mentioned above. In the first snippet where we have declared the service we have added the 'users' to the reference of the service i.e. this keyword. Whereas, in the .factory declaration, we have used the testFactory object and assigned property users to it. While using the Services in the injection, we will have the object instance of the service become  the reference to the methods and can be used in the injection for other controllers or services, while in the case of factory, when that is injected, the value is directly provided which is returned by the function within.

The above discussed are explicit or user-defined services, now let's see the in-built services provided by the Angular. (Some of them),

 

  • $http: This is the Http server requesting service, which is one of the most commonly used and important service.
    1. var app = angular.module('TestApp', []);  
    2. app.controller('TestCtrl', function($scope, $http)  
    3. {  
    4.     $http.get("url").then(function(response)  
    5.     {  
    6.         $scope.testData = response.data;  
    7.     });  
    8. });  
    As we see in the above snippet, the $http service is used to make a get request to the URL specified and then the data retrieved is assigned to the scope. As we see the $http is passed into the controller function as an argument. It is recommended to use the $http, server request inside the service as we are in a way interacting with the data. Then the service is injected into the Controller.

  • $interval: This as the name suggests, is an angular type for window.setInterval,
    1. var app = angular.module('TestApp', []);  
    2. app.controller('TestCtrl', function($scope, $interval)  
    3. {  
    4.     $scope.theTime = new Date().toLocaleTimeString();  
    5.     $interval(function()  
    6.     {  
    7.         $scope.theTime = new Date().toLocaleTimeString();  
    8.     }, 1000);  
    9. }); //reference for use from http://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_interval  
  • $location: Same as above, angular version of window.location.

  • $timeOut: Same as above, angular version of window.setTimeOut.

Dependency Injection

This is an interesting and most debated topic and Angular provides this out of the box concept.

 Out of the box

Dependency is required when we are looking for the loosely coupled codes, i.e. without directly exposing our services. The separation of concern is the major concern when DI comes into picture. Once our service is ready, we can inject to any other service or controller in Angular. The best example would be a Bakery shop.

Lets chalk out the plan with a simple snippet:

  1. var app = angular.module('BakeryApp', []);  
  2.    
  3. app.service('BakeryService', function() {  
  4.     //Declare or pass the prices as arg   
  5.     this.Pizza = function(quantity) { return quantity * pizzaPrice };       
  6.     this.Pastries =function(quantity) { return quantity * pastriesPrice };       
  7.     this.Cakes= function(quantity) { return quantity * cakePrice};  
  8. });  
  9.   
  10. //Injected Bakery Service to the 'BakeryCalculateService'  
  11. app.service('BakeryCalculateService', function(BakeryService){       
  12.     this.PizzaPrice = function(qty) { return BakeryService.Pizza(qty); };  
  13.     this.CakePrice= function(qty) { return BakeryService.Cakes(qty); };   
  14. });  
  15.   
  16. //Injected BakeryCalculateService.  
  17. app.controller('BakeryPriceController', function($scope, BakeryCalculateService) {   
  18.     $scope.CalcPizzaRate= function() {  
  19.         $scope.PizzaRate = BakeryCalculateService.PizzaPrice ($scope.quantity);  
  20.     }   
  21.     $scope.CalcCakeRate= function() {  
  22.         $scope.answer = BakeryCalculateService.CakePrice($scope.quantity);  
  23.     }  
  24. });  
We can see very well in the above example the Dependency Injection and the separation of the main service, the layering that is set between the controlle, and the actual operations. This is very handy during maintenance as well. This is by law which every developer should abide by.

Do's & Don'ts

Another interesting fact when we use the injection is the minification breakage. The angular code breaks when the injection is not done properly when the script files are usually bundled and minified.

The above Dependency Injection snippet we discussed will break when the script is minified, bundled & deployed. The reason being, when minification takes place, it re-frames the variable names as 'a','b','c'.., thus the parameters injected as $scope, $http will be now treated as a, b. Thus this will break as there is no meaning injecting a b, may it be a controller or a service.

To avoid that, we usually modify the snippet and use the Angular attribute $inject, wherever Dependency is injected.
  1. var testController = function(myCtrlScope, $http)  
  2.     { //We included $scope and the $http service into our controller.}  
  3.         testController.$inject = ['$scope''$http']  
Since we are using $inject attribute on our controller, it will not be an issue using any name of the parameters to it.

Conclusion

Thus, we have discussed a few interesting concepts this time and work arounds with live snippets. Still we have not discussed the integration of angular with an MVC app using API. We will discuss it in the upcoming articles of the series, before that we will be clear on the basic things that need to be covered.

I hope this article helps. I am always open for corrections and suggestions.
 
Read more articles on AngularJS:

 


Similar Articles
Invincix Solutions Private limited
Every INVINCIAN will keep their feet grounded, to ensure, your head is in the cloud