Skip to content

Instantly share code, notes, and snippets.

@alanklement
Created December 7, 2013 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanklement/7835044 to your computer and use it in GitHub Desktop.
Save alanklement/7835044 to your computer and use it in GitHub Desktop.
Data friendly, numbers only and human readable numbers for input field. This does two things: 1) Cleans data for entry into a data model as a Floating point. 2) Renders back to the user a more human readable value. See it live here with HTML: http://plnkr.co/bznBGg
var app = angular.module("myApp", [])
app.controller('Controller', function ($scope) {
$scope.input = '23423423';
});
app.directive('numbersOnly', function ($filter) {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
var cleanForModel = function (inputValue) {
if (inputValue === undefined) return 0;
var data = parseFloat(inputValue.toString().replace(/[^0-9\.]/g, '')).toFixed(2);
if(isNaN(data)) data = 0;
return data;
};
var makeHumanReadable = function(inputValue){
var cleaned = cleanForModel(inputValue);
var data = $filter('number')(cleaned,2);
return data;
};
element.bind('blur', function() {
modelCtrl.$setViewValue(makeHumanReadable(modelCtrl.$viewValue));
modelCtrl.$render();
});
modelCtrl.$parsers.push(cleanForModel);
modelCtrl.$formatters.push(makeHumanReadable);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment