AngularJs Ng-Keypress event not working correctly?

I am developing an application in Angularjs. I am using ng-keypress event in input type = text. When I enter a value in the text, I get the wrong values ​​in the keystroke function. For example, for the first time, if I type "1", I get undefined . The second time, typing any other value, you get the first value

<input ng-model="NodeId_1" type="text" ng-keypress="getValue()"/>

  var angularapp = angular.module('nameapp', []); angularapp.controller('NameCtrl', function ($scope) { $scope.getValue = function () { alert($scope.NodeId_1);//Here first time undefined is coming and second what ever we enter first value will come } } ) 
+6
source share
2 answers

Instead, you want to use ng-keyup .

ng-keypress occurs when a key is pressed, and before the value fills the input. That is why you do not get any value on the first keystroke, but on subsequent keystrokes you will.

Use ng-keyup , and your problem is solved, as it happens after the value has already filled the input.

 <input ng-model="NodeId_1" type="text" ng-keyup="getValue()" /> 

ng-keypress works as intended, but this does not apply to your requirements.

Working plunkr: http://plnkr.co/edit/OHWDZo68siDlcrXnLyzJ?p=preview

+11
source

A keypress event is fired when a key is pressed and this key usually generates a character value (use input instead). https://developer.mozilla.org/en-US/docs/Web/Events/keypress

Thus, neither the value of the input field nor the value of the scope (application cycle / digest, etc.) reflect the expected value of the input.

The decision depends on your requirements. Here are some of them:

1) Use another event in the input field: change, keyup, ...

2) Use the $ event object in the listener method:

 <input ng-model="NodeId_1" type="text" ng-keypress="getValue($event)"/> $scope.getValue = function (event) { console.log(event) } 

3) Create an observer for your NodeId_1 value within the scope:

 $scope.$watch('NodeId_1', function(newVal) { ... }); 
+3
source

Source: https://habr.com/ru/post/972224/


All Articles