按键触发方法

时间:2015-05-18 20:52:41

标签: javascript angularjs

我很难在按键上触发一个功能。

当然,Angular有这方面的文档:https://docs.angularjs.org/api/ng/directive/ngKeypress

问题是,当我在指令中传递函数时,它不会被调用。

例如:

它有效:

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

但它没有:

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

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

编辑:正确(但假)方法

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

我看到了一些类似的问题,但他们都没有使用函数的例子。

非常感谢:)

1 个答案:

答案 0 :(得分:1)

ng-keypress示例用法:

视图:

<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";
     };

});

使用ng-keypress的工作示例:https://jsfiddle.net/tbsxe80e/1/

替代方案,angularjs docs:ng-keydownng-keyup