Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect keydown or keypress event in angular.js?

I'm trying to get the value of a mobile number textbox to validate its input value using angular.js. I'm a newbie in using angular.js and not so sure how to implement those events and put some javascript to validate or manipulate the form inputs on my html code.

This is my HTML:

    <div>         <label for="mobile_number">Mobile Number</label>         <input type="text" id="mobile_number" placeholder="+639178983214" required            ngcontroller="RegisterDataController" ng-keydown="keydown">     </div>  

And my controller:

    function RegisterDataController($scope, $element) {        console.log('register data controller');        console.log($element);        $scope.keydown = function(keyEvent) {         console.log('keydown -'+keyEvent);        };     } 

I'm not sure how to use the keydown event in angular.js, I also searched how to properly use it. And can i validate my inputs on the directives? Or should I use a controller like what I've done to use the events like keydown or keypress?

like image 951
abelski Avatar asked Aug 21 '13 14:08

abelski


People also ask

How do you detect if a key is being pressed in JavaScript?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

What is the difference between Keydown and keypress events?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is Keydown event in angular?

Definition and Usage. The ng-keydown directive tells AngularJS what to do when the keyboard is used on the specific HTML element. The ng-keydown directive from AngularJS will not override the element's original onkeydown event, both will be executed.

How does angular handle keypress events?

you can easily use keypress event in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. When user will press key on input box field then trigger onKeypressEvent() of angular component. we will use (change) attribute for call function.


2 Answers

Update:

ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.

<!-- you can, for example, specify an expression to evaluate --> <input ng-keypress="count = count + 1" ng-init="count=0">  <!-- or call a controller/directive method and pass $event as parameter.      With access to $event you can now do stuff like       finding which key was pressed --> <input ng-keypress="changed($event)"> 

Read more here:

https://docs.angularjs.org/api/ng/directive/ngKeypress https://docs.angularjs.org/api/ng/directive/ngKeydown https://docs.angularjs.org/api/ng/directive/ngKeyup

Earlier solutions:

Solution 1: Use ng-change with ng-model

<input type="text" placeholder="+639178983214" ng-model="mobileNumber"  ng-controller="RegisterDataController" ng-change="keydown()"> 

JS:

function RegisterDataController($scope) {           $scope.keydown = function() {         /* validate $scope.mobileNumber here*/    }; } 

Solution 2. Use $watch

<input type="text" placeholder="+639178983214" ng-model="mobileNumber"  ng-controller="RegisterDataController">      

JS:

$scope.$watch("mobileNumber", function(newValue, oldValue) {     /* change noticed */ }); 
like image 85
AlwaysALearner Avatar answered Sep 19 '22 14:09

AlwaysALearner


You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.

The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):

var mod = angular.module('mydirectives'); mod.directive('onKeydown', function() {     return {         restrict: 'A',         link: function(scope, elem, attrs) {              // this next line will convert the string              // function name into an actual function              var functionToCall = scope.$eval(attrs.ngKeydown);              elem.on('keydown', function(e){                   // on the keydown event, call my function                   // and pass it the keycode of the key                   // that was pressed                   // ex: if ENTER was pressed, e.which == 13                   functionToCall(e.which);              });         }     }; }); 

The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:

<input type="text" on-keydown="onKeydown"> 

And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:

$scope.onKeydown = function(keycode){     // do something with the keycode } 

Hopefully that helps either you or someone else who wants to know

like image 22
tennisgent Avatar answered Sep 20 '22 14:09

tennisgent