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

$parsers and $formatters in Angularjs

$parsers and $formatters are array of function defined on ngModelController . When there is change in values (view or model), the value is passed through the $parsers or $formatters pipeline to convert it according to the needs. $parsers (View to Model): $parsers is an array of function which executes when there is change in view  value ( $veiwValue ), usually via user input. $parsers cause the conversion of view value into the form desirable to assign in model value. The value is passed through each $parsers function and the return value of one function is passed to next function. Last return value is passed to $validators and after validation the value is assigned to model. These $parsers functions are called array order (i.e. index 0 to n). $parsers are not called when there is change in model value programmatically. $parsers function must return some value. If it not, causes parse error and model value is set to undefined . Let's see the simple ...

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=...

Dive into ngIf directive and ngShow directive with example

ngIf and ngShow directives are used very frequently in Angular apps. Here will the difference between these two through an example. Firstly, let's see the main difference between these two as in angular docs: ngIf differs from ngShow and ngHide in that ngIf completely removes and recreates the element in the DOM rather then changing its visibility via display css property. The main points are as follows: ngShow directive uses css display property to show and hide the element in DOM. It does't remove the element from the DOM. It just set class="ng-hide" to hide the element and removes the ng-hide class to show the element. ngIf directive remove and reinsert the element based on the expression provided in ng-if directive. The inserted element has the state which was initialized at the time of compilation. If we change any css property of the element or set any class, that css property and class will be lost if the ng-if expression becomes false and...