Is it possible to simulate a keypress in AngularJS?

Viewed 320

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 Answers

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;
      }
    }
  };
});
Related