Skip to main content

Angular service to handle form input elements

In the previous post, we have seen how the datatype mismatch cause an error in HTML5 Angularjs Form. We have see the remedy to remove those errors. Each time when we send and $http request to insert and item to MySQL database we have to convert the data according to the data format accepted by the database. If in our form has less number of input fields then we can change the data format of form data submit to server by converting each value.

It is tedious to convert the data format for each input field if we have many input to handle. In that situation, we will make our code dirty and less maintainable and readable. To overcome all these type of difficulties, we have created an angular service to tackle it. Let's see the code for our angular service named $convertor:
$convertor Service:

var app = angular.module('myApp',[]);
app.factory('$convertor',['dateFilter',function(dateFilter){
  return{
    convertForSQL : convertForSQL,
    convertForHTML5 : convertForHTML5
  };

  function convertForSQL(obj){
    var o = angular.copy(obj);
    angular.forEach(o, function(value, key){
      if(angular.isDate(value)){
        o[key] = dateFilter(value,'yyyy-MM-dd');
      }
    });
    return o;
  }

  function convertForHTML5(o){
    angular.forEach(o, function(value, key){
      if(isValidDate(value)){
        o[key] = new Date(value);
      }
      if(isValidNumber(value)){
        o[key] = parseFloat(value);
      }
      if(angular.isObject(value) || angular.isArray(value)){
        o[key] = convertForHTML5(value);
      }
    });
    return o;
  }

  function isValidDate(dateString) {
    var regEx = /^\d{4}-\d{2}-\d{2}$/;
    if(!dateString.match(regEx)) 
      return false;  // Invalid format
    var d = new Date(dateString);
    if(!d.getTime()) 
      return false; // Invalid date (or this could be epoch)
    return d.toISOString().slice(0,10) === dateString;
  }

  function isValidNumber(numberString){
    var regEx = /^[+-]?((\.\d+)|(\d+(\.\d+)?))$/;
    if(!numberString.match(regEx)) 
      return false;
    return true;
  }
}]);

The $convertor service has a two functions:
#1. convertForSQL - This function is used to convert the angular form data to be accepted by the MySQL database. This method is called before the data passed to $http configuration data value. See below:

 data : $httpParamSerializerJQLike( $convertor.convertForSQL(data) )

#2. convertForHTML5 - This method is used to convert the JSON object to make it accepted by angular form inputs. This is called on the response data return by the $http call. See below:
 $http({...})
  .then(
    function(response){
      $scope.response = $convertor.convertForHTML5(response.data);
  });

How to use $convertor service:
The $convertor service is to be injected into controller for using it. Here is code for complete usage:

app.controller('myAppCtrl', function($scope, $http, $convertor, $httpParamSerializerJQLike){
  $scope.formData = {};
  $scope.response = {};

  $scope.submitForm = function(){
    var item = $convertor.convertForSQL($scope.formData);
    $http({
      method : 'POST',
      url : 'process.php',
      data : $httpParamSerializerJQLike(item),
      headers : {'Content-Type':'application/x-www-form-urlencoded'}
    })
      .then(
        function(response){
          $scope.response = $convertor.convertForHTML5(response.data);
      });
  };
});
Happy Coding :)

Comments

Popular posts from this blog

Code Syntax Highlighting on Blogger using Prismjs

Prismjs is developed by Lea Verou. It is a lightweight, extensible syntax highlighter, built with modern web standards in mind. It’s used in thousands of websites, including some of those you visit daily.Today, we will see how to use the prismjs on blogger to highlight our codes. It very easy and step by step process to follow: Goto to this link and get the personalized links for prismjs or simply copy the links given below: <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/themes/prism-coy.min.css" rel="stylesheet"></link> <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/prism.min.js"></script> Goto Theme > Edit HTML and paste the links before the closing </head> section as shown below: Default prism.min.js file contain the functionality to highlight the code for only HTML, CSS and JS code. If you wish to use other language to highlight, you have to paste the link for that langu...

Automatic Slashing the Date Input using Angularjs

We define a directive that will automatically slash the input field as user typein the date. The directive have following capabiltiy: The directive will append slash '/' when input field has 2 or 5 characters. The input will accept only 10 characters (dd/mm/yyyy). Validity of date provide will not be checked. When the backspace is pressed it will remove the last two character if last character is slash. Otherwise it will remove last character from the input field. The input will not accept characters other than numbers (0 to 9). Let's jump into the code. We will use bootstrap for awesome look: HTML Code: <div class="container" ng-app="myApp" ng-controller="myAppCtrl"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <form class="form-horizontal"> <h4 class="bg-primary">Auto Slashing Date using Angularjs Directive</h4> <div class=...

Lifecyle hooks in Angular

Each Angular component goes through a lifecycle. This is managed by the Angular itself. Angular creates a component, renders it, creates and renders its children, looks for the changes in its data-bound properties and destroys it. Angular has lifecycle hooks for each such key moment and provide a way to act accordingly when such moment happens. Directive and component have a lifecycle. For each lifecycle moment, Angular provides a lifecycle hook . The developer can hook into such moment by implementing the one or more specific lifecycle interfaces from the Angular core. Angular provide following lifecycle hooks as under: ngOnChanges ngOnInit ngDoCheck ngAfterContentInit ngAfterContentChecked ngAfterContentInit ngAfterContentChecked ngOnDestroy   Sequence of execution of the lifecycle hooks During the creation of component: Constructor ngOnChanges ngOnInit ngDoCheck ngAfterContentInit ngAfterContentChecked ngAfterContentInit ngAfterContentChecked During chang...