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?

1 Answer 1

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;
      }
    }
  };
});
Sign up to request clarification or add additional context in comments.

7 Comments

This works for text. How would you write it for decimal? This is exactly what I'm looking for.
you can replace all non-decimals
var newVal = val.replace(/,/g, '.').replace(/[^\d.]/g, '');
@Saman Using $parsers you can handle the input anyway you wish, just write there conditions you need
$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 jsfiddle.net/gudzdanil/un56mjez/13
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.