I created a custom directive to only allow float numbers as input:
.directive('floatOnly', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue === undefined) return '';
// Removing invalid characters
cleanInputValue = inputValue.replace(',', '.') // converting commas to dots
.replace(/[^\d.]/g, '') // keeping only numbers and dots
.replace(/\./, "x") // replacing the first dot with X
.replace(/\./g, "") // removing all other dots
.replace(/x/, "."); // changing X back to dot
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
To use this directive, insert the following code in your HTML:
<input type="text" ng-model="myFloat" float-only/>
Test snippet:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
}]).directive('floatOnly', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue === undefined) return '';
// Remove forbidden characters
cleanInputValue = inputValue.replace(',', '.') // change commas to dots
.replace(/[^\d.]/g, '') // keep numbers and dots
.replace(/\./, "x") // change the first dot in X
.replace(/\./g, "") // remove all dots
.replace(/x/, "."); // change X to dot
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Float only: <input type="text" ng-model="myFloat" float-only/>
</div>
</div>
Test the functionality by entering different inputs into the text field