2

I need to get Dot (.) written on an input whenever Comma (,) is pressed for decimal input and not text. I need somehow to simulate Keypress or KeyDown programmatic.

I tried all the answers here but none of them worked:

I wrote the following directive code for an input:

app.directive('ngKommatopoint', function() {
    return {
      link : function($scope, element, attrs) {
              element.bind("keydown keypress", function(event) {
                      if(event.which === 188) {
                          element.trigger(
                              $.Event( 'keydown', { keyCode:190,which:190})
                          );
                     }
                  });
          },
    restrict: 'A'
  };  });

This solution doesn't work because it never calls "Dot" event. Any idea why it doesn't work?

Saman
  • 439
  • 7
  • 16

1 Answers1

2

Use parsers/formatters instead on ngModelController to intercept user input.

Your solution will skip copy/paste but parsers/formatters will not.

https://dzone.com/articles/parsers-and-formatters-custom

You can handle all the changes to model and parse it as you need

Update

Here is fiddle: https://jsfiddle.net/gudzdanil/un56mjez/2/


app.directive('nodot', function(){
  return{
    require:'ngModel',
    link: function(scope, elem, attrs, ctrl){
      ctrl.$parsers.unshift(replace);
      function replace(val){
        var newVal = val.replace(/,/g, '.');
                ctrl.$viewValue = newVal;
        ctrl.$render()
                return newVal;
      }
    }
  };
});
Danil Gudz
  • 2,233
  • 16
  • 16
  • This works for text. How would you write it for decimal? This is exactly what I'm looking for. – Saman Jan 14 '19 at 14:42
  • you can replace all non-decimals – Danil Gudz Jan 14 '19 at 14:45
  • `var newVal = val.replace(/,/g, '.').replace(/[^\d.]/g, '');` – Danil Gudz Jan 14 '19 at 14:46
  • @Saman Using $parsers you can handle the input anyway you wish, just write there conditions you need – Danil Gudz Jan 14 '19 at 14:48
  • Thanks. Is there a way to prevent multiple dots like a decimal number? Having only one dot? – Saman Jan 14 '19 at 14:53
  • This works perfectly with Angular "1.2.1", but not for newer versions like "1.7.2" – Saman Jan 15 '19 at 07:57
  • 1
    $commitViewValue method fixes issue as after value update on parser processing in the next step parsers compares prev view value and the current one so that on the second input parsers are not executed as prev value equals the current one. Check the update https://jsfiddle.net/gudzdanil/un56mjez/13/ – Danil Gudz Jan 15 '19 at 08:23