0

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.

Dave Long
  • 9,569
  • 14
  • 59
  • 89
  • 1
    possible duplicate of [HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?](http://stackoverflow.com/questions/18677323/html5-input-type-number-value-is-empty-in-webkit-if-has-spaces-or-non-numeric-ch) – jantimon Jul 16 '14 at 20:32
  • 2
    I believe you will have a hard time with this due to the implementation of the number type, specifically with Google Chrome. If a number field contains a non-numeric value, it is seen as invalid and has an internal value of ''. – TheSharpieOne Jul 16 '14 at 20:46
  • In case somehow you really get it works (e.g. by changing to use type="text"), don't forget to add a formatter to `ctrl.$formatters` as well to ensure the two-way binding won't break. – runTarm Jul 17 '14 at 04:30

1 Answers1

0

It seems that my issue is not related to Angular, but to the browser implementation of input[type=number]. The value attribute is set to null in Chrome if the value is not a number.

HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?

Community
  • 1
  • 1
Dave Long
  • 9,569
  • 14
  • 59
  • 89