Thousands Formatter directive
format input field for currency, but leave model value as regular input.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<div ng-app='myApp'>
<div ng-controller="myCtrl">
<input ng-model="dollars" thousandsformatter autofocus></input>
{{dollars}}
</div>
</div>
JavaScript
var myApp = angular.module('myApp', []);
function myCtrl($scope) {
$scope.dollars = null;
}
myApp.directive('thousandsformatter', function ($filter) {
var precision = 2;
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$formatters.push(function (data) {
var formatted = $filter('currency')(data);
console.log(formatted);
//convert data from model format to view format
return formatted; //converted
});
ctrl.$parsers.push(function (data) {
var plainNumber = data.replace(/[^\d|\-+|\+]/g, '');
var length = plainNumber.length;
var intValue = plainNumber.substring(0,length-precision);
var decimalValue = plainNumber.substring(length-precision,length)
var plainNumberWithDecimal = intValue + '.' + decimalValue;
//convert data from view format to model format
var formatted = $filter('currency')(plainNumberWithDecimal);
element.val(formatted);
return Number(plainNumberWithDecimal);
});
}
};
});