Ramasamy Kanna
Ramasamy Kanna

Reputation: 792

AngularJs Ng-Keypress event working wrongly?

I am developing an application in Angularjs. I am using ng-keypress event in input type=text. While typing value in text I'm getting wrong values in the keypress function. For example, the first time if I type "1" I am getting undefined. Second time, typing any other value gives 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
        }
    }
 )

Upvotes: 8

Views: 13660

Answers (3)

Jorge Santos Neill
Jorge Santos Neill

Reputation: 1785

The watcher function work for me, I attached my example

$scope.$watch('itemm.montoAmodificar', function (newValue) {
    $scope.fnActualizarNuevoSaldoDependencia(parseFloat(newValue));
});

The html code is the following

<input ng-model="itemm.montoAmodificar" my-focus class="form-control" type="text" placeholder="Ingrese el monto" ng-keypress="fnActualizarNuevoSaldoDependencia($event);" />

Upvotes: 0

Zhonk
Zhonk

Reputation: 634

The keypress event is fired when a key is pressed down and that key normally produces a character value (use input instead). https://developer.mozilla.org/en-US/docs/Web/Events/keypress

So neither the input field value nor the scope value(apply/digest loop etc.) will reflect the expected input value.

Solution is depending on your requirements. Here are some:

1) Use another event on the inputfield: change, keyup, ...

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

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

$scope.getValue = function (event) {
    console.log(event)
}

3) Create a watcher for your NodeId_1 value within your scope:

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

Upvotes: 3

Shelby L Morris
Shelby L Morris

Reputation: 726

You'll want to use ng-keyup instead.

ng-keypress happens as the key is pressed, and BEFORE the value populates the input. This is why you're not getting any value on the first keypress, but on subsequent presses you will.

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

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

ng-keypress is working as intended, but it is not the directive applicable to your requirements.

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

Upvotes: 12

Related Questions