I'm trying to write a custom directive for inputs that will modify the model so that if a user types a number as "25,000" into the input, the model ends up with the value "25000" in integer form.
I have this code so far:
<div ng-app="myApp">
<div ng-controller="SomeController">
<input type="number" name="some-field" ng-model="numericValue" integer />
</div>
</div>
<script>
app = angular.module('myApp')
app.directive('integer', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, elm, attr, ctrl) {
if (!ctrl) { return; }
ctrl.$parsers.unshift(function (value) {
return parseInt(value.replace(/\D/g, ''), 10);
});
}
};
});
app.controller('SomeController' ['$scope', function ($scope) {});
</script>
The directive will replace any non-numeric value in the value and run it through the parseInt
method before returning the value. Problem is that the value
argument of the parser method is always null
, no matter what. Not sure if I'm using the wrong function or if there's something else wrong with my code.
Edit I created a sample of my app on jsFiddle. Try things like adding commas to the fields and see what the output becomes. I've found that a major part of the issue seems to be the numeric field type. When I use a text field type, then it works fine.