Skip to content

Instantly share code, notes, and snippets.

@MikeyBurkman
Last active April 27, 2017 19:24
Show Gist options
  • Save MikeyBurkman/c6f70f9a0cc14627444594df1499a5e5 to your computer and use it in GitHub Desktop.
Save MikeyBurkman/c6f70f9a0cc14627444594df1499a5e5 to your computer and use it in GitHub Desktop.
Angular Currency Input
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</head>
<body ng-app="fooApp">
<div ng-controller="MyController">
<input as-currency ng-model="amount" /> <br>
Actual Model Value: {{amount}} <br>
</div>
<script>
(function(angular) {
'use strict';
angular.module('fooApp', [])
.directive('asCurrency', function(currencyFilter) {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ctrl) {
// When the user clicks on the field, we remove all the formatting.
// This makes it easier to edit.
elem.on('focus', renderPlainText);
// When losing focus, render it properly.
elem.on('blur', renderFormattedText);
// Runs on element load
ctrl.$formatters.push(currencyFilter);
// Runs on element load
ctrl.$parsers.unshift(function(a) {
return sanitize(a);
});
// Remove non number chars
function sanitize(s) {
if (s) {
return s.replace(/[^\d|\-+|\.+]/g, '');
}
}
function renderPlainText() {
var plain = sanitize(ctrl.$viewValue);
ctrl.$setViewValue(plain);
ctrl.$render();
}
function renderFormattedText() {
var plain = sanitize(ctrl.$viewValue);
ctrl.$setViewValue(currencyFilter(plain));
ctrl.$render();
}
}
};
})
.controller('MyController', function($scope) {
$scope.amount = '25.00';
});
})(window.angular);
</script>
</body>
</html>
@MikeyBurkman
Copy link
Author

This is an angular currency input box directive. It'll format the ng-model as currency, while keeping the model itself as a number.

When the directive gains focus, it will be shown as a number as well, to make it easier to edit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment