SupimpaAllTheWay
SupimpaAllTheWay

Reputation: 1478

Trigger method on keypress

I'm struggling to trigger a function on keypress.

Of course Angular have docs for this: https://docs.angularjs.org/api/ng/directive/ngKeypress

the problem is that when I pass a function inside of the directive it doesnt' get called.

for example:

it works:

<input ng-keypress="count = count + 1" ng-init="count=0">
key press count: {{count}}

but it doesn't:

<input ng-keypress="someFunction()">

//function inside  the controller
function someFunction(){
  console.log("Hey there");
}

EDIT: CORRECT (BUT FAKE) METHOD

$scope.someFunction = function(){
  console.log("Hey there");
}

I saw some similar question but none of them had an example using functions.

Thanks a lot :)

Upvotes: 0

Views: 254

Answers (1)

Shehryar Abbasi
Shehryar Abbasi

Reputation: 378

ng-keypress example usage:

view:

<div ng-app='App' ng-controller="AppCtrl">

<!-- if you are trying to figure out which key was pressed: -->
<input ng-keypress="someFunction($event)">   
<p> key value: {{keyWasThis}} </p>

<!-- if you just want to know if any key was pressed: -->
<input ng-keypress="someOtherFunction()">   
<p> event: {{pressed}} </p> 

js:

angular.module('App', [])
.controller('AppCtrl', function($scope) {

    $scope.someFunction = function(event) {    // function 
      $scope.keyWasThis = event.which;
     }; 

    $scope.someOtherFunction = function() {    // function 
      $scope.pressed = "yes";
     };

});

working example using ng-keypress : https://jsfiddle.net/tbsxe80e/1/

alternatives, angularjs docs: ng-keydown, ng-keyup

Upvotes: 1

Related Questions