$parsers & $formatters

it describes about parsers and formatters

by Samar Pattanayak

HTML

<div ng-app="myApp">
  <div ng-controller="myController">
    
    <form name="myForm">
    
       {{name}}
       <input type="text" ng-model="name" name="test" my-directive />
       <input type="button" ng-click="change()" value="Change Name" />     
      <span style="color:green" ng-show="myForm.test.$error.is_valid">Max Length Reached </span>
    </form>
    
   
    
  </div>
</div>

JavaScript

var ang = angular.module("myApp", []);
ang.controller("myController", function($scope) {
  $scope.name = "";
  $scope.change = function() {
    $scope.name = "Kumar";
  }
});
//form1.value1.$error.is_validtr
ang.directive("myDirective", function() {
    return {
      restrict: "EA",
      require: 'ngModel',
      link: function(scope, ele, att, ctr) {
        var view_value;
        
        ctr.$formatters.push(function(value) {
          //return value.toUpperCase();
        });
        ctr.$parsers.push(function(value) {
          //return value.toUpperCase();     
          var return_value;

          if (value.length > 6) {
            return_value = view_value.toUpperCase();
            //these following two methods will not allow to edit in view after the specified length and everytime you type and its length it beyond 6 , setViewValue methos will set view value to the last model value. 
            ctr.$setViewValue(view_value);
            ctr.$render();
            ctr.$setValidity('is_valid', false);
          } else {
            return_value = value.toUpperCase();
            view_value = return_value;
            ctr.$setValidity('is_valid', true);
          }

          return return_value;
        });
      }
    }
  })
  //ang.filter("filterA", function(){
  //return function(input){
  //return input.toUpperCase();
  //}
  //})
//ngModel.$validators.functionName= function(mv,vv){
	 //var input= mv || nv ;
   //return input.toUpperCase();
//}