Wednesday, 22 March 2017

How to define and use your own services ?


Below are 2 ways to write business logic : without service and with service
See second one to check How to define and use the your own Service.

1. Writing business logic directly in Controller - Without a Service
   Here, Controller is complex and long

JS
app.controller("myController", function ($scope) {
   $scope.transform = function (input) {

      var output = "";
      console.log("Processing inside controller ...");
      for(var i=0; i<input.length; i++) {
         if(input[i] == input[i].toUpperCase()){
            output = output + " ";
         }
         output = output + input[i];           
      }

      return output;

       }
});



HTML
<div ng-controller="myController">
  <input type="text" ng-model="input" />
  <br/> Output :
  <input type="text" ng-model="output" />
  <input type="button" ng-click="transform(input)" value="Transform" />
</div>




2. Writing business logic in Service and call from Controller
   Here, Controller is clean and short. The service is reusable.

JS
app.controller("myController", function ($scope, transformService) {
   $scope.transform = function (input) {

        $scope.output = transformService.process(input);
       }
});



app.factory('transformService', function() {
    return {
        process : function (input) {
           var output = "";
           console.log("Processing inside Service ...");
           for(var i=0; i<input.length; i++) {
              if(input[i] == input[i].toUpperCase()){
                 output = output + " ";
              }
              output = output + input[i];
           }

           return output;
        }
    }; 
});


Service is defined using : 
<module>.factory('<serviceName>',
       function(){ return{
           <FunctionName>:<Function>(<params>) {
               ....
           }
       }; } )

Call service inside controller :
<serviceName>.<FunctionName>(<params>);

Tuesday, 21 March 2017

What are the services, its need and benefits ?


SERVICES
  • Service is an object which provides some services like, Utilities, Business logic
    Examples : $http, $log,
  • Services can be reused in Controllers, custom Directives and custom Filters.
  • Custom services can also be created

NEED OF SERVICE
  • Controller should not do all the business logic or a complex logic.
    Instead, it must call different services in order to perform action.

BENEFITS
  • Reusability - Reusable in Controllers, Directives and Filters
  • Dependency injection - can be injected in Controller
  • Easy to Test - Pass mock objects to test services

How to use $log service ?


$log is a built-in service that can be used to log the message in Web browser console.
  1. Inject the service in controller function
  2. Use $log.info function to log the messages

app.controller("myController", function ($scope, $http, $log) {
   $http( { 

       method: 'GET',
       url:'EmployeeService/GetAllEmployees' })
   .then( function(response) {
       $scope.employees = response.data;

       $log.info(response);
   });
});


Logs can be checked using Developer tools.
 

What is the default transformation of JSON and JS objects ?


Default transformation by AngularJS

1. Request configuration given as a JS object is auto-converted to JSON objects.
Example
$http({
       method: 'GET',
       url: 'EmployeeService/GetAllEmployees'
})

2. Similarly, A JSON response is auto-converted into a JS object.
Example
$http.get('EmployeeService/GetAllEmployees')
        .then( function(response) {
                   $scope.employees = response.data;
               } ,
function(reason) {
                   $scope.error = reason.data;
               } );


How to use $http service to make HTTP requests ?


$http is a built-in service which takes a configuration object as parameter.
All properties supported : https://docs.angularjs.org/api/ng/service/$http#usage

Example
$http({
   method: 'GET',
   url: 'EmployeeService/GetAllEmployees'
});



JS (Using get method of $http)
Without then function
app.controller("myController", function ($scope, $http) {
  
$scope.employees = $http.get('EmployeeService/GetAllEmployees');
});

With then function
app.controller("myController", function ($scope, $http) {
   $http.get('
EmployeeService/GetAllEmployees')
        .then( function(response) {
           $scope.employees = response.data;
        });
});



JS (Using $http service as a function)
app.controller("myController", function ($scope, $http) {
   $http( { 

       method: 'GET',
       url:'EmployeeService/GetAllEmployees' })
   .then( function(response) {
       $scope.employees = response.data; 
   });
});



Multiple functions to handle success and error callbacks
app.controller("myController", function ($scope, $http) {
   $http.get('
EmployeeService/GetAllEmployees')
        .then( function(response) {
                   $scope.employees = response.data;
               } ,
function(reason) {
                   $scope.error = reason.data;
               } );
});


OR

app.controller("myController ", function ($scope, $http) {
   var successFunc = function (response) {

       $scope.employees = response.data;
   }

   var errorFunc = function (reason) {
       $scope.error = reason.data;
   }

   $http.get('EmployeeService/GetAllEmployees').then(successFunc, errorFunc);

});
OR

   $http({
       method: 'GET',
       url: 'EmployeeService/GetAllEmployees'
   })
   .then(successFunc, errorFunc);

Sunday, 19 March 2017

How to use ng-include to include another HTML page ?


ng-include directive is used to include another HTML page in current HTML page - Reusability

It can take a static value (A HTML page) or a dynamic value (using variable set in $scope)
<div ng-include="'Result.html'"> </div>
OR
<div ng-include="resultPage"> </div>

SAMPLE HTML TO INCLUDE
Result.html 
<table>
   <thead>
      <tr> <th>Name</th> <th>Post</th> <th>Salary</th> </tr>
   </thead>
   <tbody>
      <tr ng-repeat="employee in employees">
         <td> {{ employee.name }} </td>
         <td> {{ employee.gender
}} </td>
         <td> {{ employee.salary }} </td>
      </tr>
   </tbody>
</table>



EXAMPLE 1. USING STATIC VALUE FOR VIEW
Main.html
<div ng-controller="myController"> 
  <div
ng-include="'Result.html'"> </div>

</div>



EXAMPLE 2. USING DYNAMIC VALUE FROM SCOPE PROPERTY
JS
var app = angular.module('module1', []);

app.controller("myController", function ($scope) {
   var employees = [

        { name : "Shaan", city : "Jhansi", salary : 25000 },
        ...

     ]
 
   $scope.employees = employees;

   $scope.empView = "Result.html";
});



Main.html
<div ng-controller="myController"> 
  <div
ng-include="empView"> </div>

</div>



EXAMPLE 3. USING DYNAMIC VALUE THROUGH DROP DOWN CHOICE
Main.html
<div ng-controller="myController"> 

  Select view :
  <select ng-model="empView">
      <option value="Result1.html">Result 1</option>
      <option value="Result2.html">Result 2</option>
  </select>  <br/> <br/>

  <div ng-include="empView"> </div>
</div>