JSFiddle - React, Tailwind, and code Playground
by dandoyon
HTML
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
Num <input currency ng-model="num"></input>
</div>
JavaScript
var app = angular.module("myApp", [])
var CURRENCY_REGEXP = /^\-?\d+(\.?\d?\d?)?$/;
app.directive('currency', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (CURRENCY_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('currency', true);
console.log("valid");
return viewValue * 100;
} else if (viewValue === '') {
return 0;
} else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('currency', false);
console.log("invalid");
return undefined;
}
});
ctrl.$formatters.push(function(modelValue) {
console.log('calling formatter');
if (modelValue === 0) { // we're using integer pence, so this is safe
return '';
}
return (modelValue / 100).toFixed(2);
});
elm.bind('blur', function() {
console.log('rendering ctrl', ctrl);
scope.$apply(function() {
ctrl.$render();
});
});
}
};
});
function MyCtrl($scope) {
$scope.num = 10.00;
}