使用Angularjs中的按键调用函数

时间:2015-11-24 11:37:08

标签: javascript jquery html angularjs angularjs-scope

我有一个使用ng-click="startChat()"在div标签内调用的方法 - 它工作正常。

我希望在按下一个键的同时调用相同的函数,在这种情况下,假设'p'的密钥代码为112.

我尝试将以下内容添加到div:

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

我也尝试过与ng-keyupp相同但没有任何反应。有人知道为什么以及如何完成任务?

3 个答案:

答案 0 :(得分:3)

您必须将ng-keydown的操作视为对控制器中的$ scope或指令的link部分中的函数的函数调用。下面的代码对我有用。

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

$scope.doSomething= function($event){
    var key = $event.keyCode;
    console.log(key)
}

答案 1 :(得分:0)

您可以使用ng-keypress执行此操作。在此调用一个函数并检查keyCode。

答案 2 :(得分:0)

尝试使用指令:

<强> 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>

字体:How to use a keypress event in AngularJS?

我们简单的按键

演示:

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>