Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-controller="MyCtrl">
<div>Raw Value: {{currencyVal}}</div>
<div>Filtered Value: {{currencyVal | number}}</div>
<input type='text' currency-input = "" ng-model = "currencyVal"/>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.currencyVal = 123456;
});
myApp.directive('currencyInput', function($filter, $browser) {
return {
require: 'ngModel',
link: function($scope, $element, $attrs, ngModelCtrl) {
$element.addClass('numberInput');
var separators = {
'thousands' : $filter('number')(1000).substr(1,1),
'decimal' : $filter('number')(1.1).substr(1,1)
}
var decimalEntered = false;
var listener = function() {
var value = $element.val().split(separators.thousands).join('').split(separators.decimal).join('.');
if(decimalEntered) {
decimalEntered=false;
return;
}
if(value.indexOf('.')>1 && value.slice(-1)=='0') {$element.val(value); return;}
$element.val($filter('number')(value));
}
// This runs when we update the text field
ngModelCtrl.$parsers.push(function(viewValue) {
return viewValue.split(separators.thousands).join('').split(separators.decimal).join('.');
})
// This runs when the model gets updated on the scope directly and keeps our view in sync
ngModelCtrl.$render = function() {
$element.val($filter('number')(ngModelCtrl.$viewValue, false))
}
$element.bind('change', listener)
$element.bind('keypress', function(event) {
var key = event.which;
// If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
// This lets us support copy and paste too
if (key == 0 || key == 8 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
return
}
// ignore all other keys which we do not need
if (
String.fromCharCode(key) != separators.thousands
&& String.fromCharCode(key) != separators.decimal
&& !(48 <= key&&key <= 57)
&& String.fromCharCode(key) != '-'
) {
event.preventDefault();
return;
}
if (String.fromCharCode(key)==separators.decimal)...