Last active
April 27, 2017 19:24
-
-
Save MikeyBurkman/c6f70f9a0cc14627444594df1499a5e5 to your computer and use it in GitHub Desktop.
Angular Currency Input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.