Created
December 7, 2013 00:13
-
-
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
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
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