0

I have a method that gets called inside a div tag using ng-click="startChat()" - it works fine.

I would like the same function to be called there when pressing down a key, let's say 'p' in this case which has a keycode of 112.

I tried adding the following to the div:

ng-keydown="$event.keyCode == 112 ? startChat()"

I also tried the same with ng-keyupp but nothing happens. Does someone know why and how can I achieve the task?

Coding Learner
  • 5
  • 1
  • 1
  • 6
  • Possible duplicate of [How to use a keypress event in angularjs](http://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs) – Niranjan Singh Nov 24 '15 at 11:48

3 Answers3

3

You have to treat the action of the ng-keydown as a function call to either your $scope in the controller or a function in your link section of the directive. Code below works for me.

<input type="text" ng-keydown='doSomething($event)'>

$scope.doSomething= function($event){
    var key = $event.keyCode;
    console.log(key)
}
sillysicko
  • 126
  • 7
0

You can do this with ng-keypress. Call a function on this and check for the keyCode.

kipzes
  • 694
  • 2
  • 10
  • 27
0

Try with directive as:

JS:

app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});

HTML:

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" my-enter="doSomething()">    
</div>

Font: How to use a keypress event in AngularJS?

Our simple keypress

Demo:

function myController($scope) {
  $scope.lastKey = "---"

  $scope.keypress = function($event) {
    $scope.lastKey = $event.keyCode
  };
    
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <h2>Example</h2>
  <div ng-controller="myController">

      <p>The new ng-keydown directive works perfectly fine as long as it is bound to an input field. Type to see keyCode: </p>
      <input ng-keydown="keypress($event)">
          <p>last key: {{lastKey}}</p>
          <div ng-keydown="keypress($event)" style="border: 1px solid blue;">
<p>Focusing this div (blue border) and typing however does not work, in spite of the documentation saying that the context for ng-keydown can be anything: http://code.angularjs.org/1.1.3/docs/api/ng.directive:ngKeydown</p>
<p>I can't seem to get it to cooperate unless there is an input field:
<input>
    </p>
    <p>How can I use ng-keydown for the entire document or selected spans, etc.?
    </p>
          </div>
  </div>
</div>
Community
  • 1
  • 1
Emir Marques
  • 2,603
  • 2
  • 16
  • 22