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

Auto generating the year in select using ngOption

While creating an angular form, we come upon a situation where we required to generate the sequence of years in the select HTML tag. There is some way to perform this task, but each has its limitation. Let's look the way to generate the years : Hard code an array having years in your controller and assign it to some $scope variable. Use for loop to generate the years and then assign to $scope variable. Send $http request to generate the array of year and assign the response data to $scope variable. Define a filter that will be used to generate the sequence of years. As the first and second method makes our controller dirty and the third method causes HTTP request that will overhead server, so we are going to see the fourth method to generate the years as it has several advantages over other three methods. So let's jump into the code: HTML Code: <form name="myform"> <select ng-options="year for year in [] | range: '2000':'20...