Skip to content

Instantly share code, notes, and snippets.

@akanieski
Created October 18, 2013 22:43
Show Gist options
  • Save akanieski/7049337 to your computer and use it in GitHub Desktop.
Save akanieski/7049337 to your computer and use it in GitHub Desktop.
AngularJS Decimal Only Directive
angular.module('myApp.directives', []).directive('currency', function () {
return {
restrict: 'A',
transclude: false,
require: '^ngModel',
scope: false,
controller: function ($scope, $element, $attrs) {
$scope.$watch($attrs.ngModel, function (newValue, oldValue) {
var val = newValue.toString().replace(/[^\d.-]/g, '');
val = val.length > 0 ? val : '""';
while (val.split(".").length - 1 > 1)
val = val.replace('.', '');
while (val.split("-").length - 1 > 1)
val = val.replace('-', '');
switch (val.substr(val.length - 1)) {
case '.':
val = '"' + val + '"';
break;
case '-':
val = '"' + val + '"';
break;
case '0':
val = '"' + val + '"';
break;
}
eval('$scope.' + $attrs.ngModel + ' = ' + val + '');
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment