ngCurrencyInput Directive
by Thomas Langston
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-controller="MyCtrl">
<div class="header">
AngularJs directive for automatic formatting of currency values in input fields.
</div>
With 2 decimal places
<input type='text' ng-currency-input ng-model="numericValue" />
</div>
CSS
.header {
font-weight: bold;
margin-bottom: 15px;
padding: 15px;
}
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.numericValue = 12345678;
});
// Original code taken from the following fiddles:
// http://jsfiddle.net/KPeBD/2/
// http://jsfiddle.net/davidvotrubec/ebuqo6Lm/
myApp.directive('ngCurrencyInput', ['$filter', '$locale', function($filter, $locale) {
return {
require: 'ngModel',
restrict: "A",
link: function($scope, element, attrs, ctrl) {
var fractionSize = 2;
var numberFilter = $filter('number');
ctrl.$formatters.push(function(modelValue) {
var retVal = numberFilter(modelValue, fractionSize);
var isValid = isNaN(modelValue) == false;
ctrl.$setValidity(attrs.name, isValid);
return retVal;
});
ctrl.$parsers.push(function(viewValue) {
var viewDigits = viewValue.trim().replace(/[^0-9]/g, '');
console.log('viewDigits', viewDigits);
var number = parseFloat(viewDigits) / 100.0;
if (isNaN(number) == false) {
var newViewValue = numberFilter(number, fractionSize);
element.val(newViewValue);
}
return isNaN(number) == false ? number : null;
});
} //end of link function
};
}]);