Parser and Formatter

http://alexperry.io/angularjs/2014/12/10/parsers-and-formatters-angular.html

by Norlihazmey Ghazali

HTML

<div ng-app="MyApp" ng-controller="MainController as MyCtrl">
	<button ng-click="hello='EMI'">SET EMI</button>
  <input type="text" ng-model="hello" my-dir/>
  {{ hello }}
</div>

JavaScript

function MainCtrl($scope, $timeout) {
  var _this = this;
	$scope.hello = 'HELLO';  
}

MainCtrl.$inject = ['$scope','$timeout'];
angular.module('MyApp', [])
.controller('MainController', MainCtrl)
.directive('myDir', function () {
	return {
		restrict : 'A',
		require : 'ngModel',
		link : function ( scope, element, attr, ngModelCtrl, transclude ) {
		  // this parsers be called when user type in textbox, 
			// which means only call WHEN change from view
			ngModelCtrl.$parsers.push(function(value){
				console.log('parser :' + value)					
				return value.toUpperCase();
			});
			// this formatter only be called when we change
			// the model value inside code,NOT from view
			ngModelCtrl.$formatters.push(function(value){
				console.log('formatter :' +  value)					
				return value.toLowerCase();
			});
		}
	}
})