Search code examples
javascriptangularjsangular-ngmodel

AngularJS : ng-model doesn't update correctly with ng-keydown. ng-model off by one character


I am looking at text input on AngularJS as it changes by the user.

However, it seems that when I print to the console from my .js, the ng-model is off by one character because there seems to be a lag with the update by one keydown.

For example: If the user types "hello" I see "hell" until another keydown is triggered, which will then update what I see to "hello" but the user input could be "helloW"

If that makes sense... Sorry.

Basically, is there a way that I can force update my ng-model from my controller so that I can see the user input as it comes in with each keydown?

I cannot post my code, sorry.


Solution

  • try using "ng-keyup" with "ng-model" instead of ng-keydown :)

    Here the doc: https://docs.angularjs.org/api/ng/directive/ngKeyup

     var app = angular.module('app',[]);
     app.controller('MyController', function ($scope) {      
        $scope.onKeyUpPrint = function(){
          // You can name the function as you want
          // scope will be triggered exactly on key Up
          console.log($scope.inputModel);
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <body ng-app="app" ng-controller="MyController">
    <h1>Use ng-keyup<h1>
    <input type="text" name="inputbox" ng-keyup="onKeyUpPrint()" ng-model="inputModel">
    </body>