javascript Angular-UI 中的按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12816420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:11:05  来源:igfitidea点击:

Keypress in Angular-UI

javascripthtmlangularjs

提问by ssb

I am running into some problems using the keypress as follows-

我在使用按键时遇到了一些问题,如下所示-

<div ng-controller="GBNController">
...
<input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/>
...
</div>

and my javascript has -

我的 javascript 有 -

var AngApp = angular.module('gbn', ['ui']);
var GBNController = function($scope) {
    $scope.queryText = '';
    $scope.foo = function() {
        alert('test');
    }
};

Now this function foo is called only when the document is loaded and then after that, the returnkeypress event in the text field is never handled.

现在这个函数 foo 仅在加载文档时调用,之后,return文本字段中的按键事件永远不会被处理。

I am using the current headof the master branch.

我正在使用主分支的当前负责人。

Am I doing something wrong here, or is this broken??

我在这里做错了什么,还是坏了??

回答by Andrew Joslin

You need to put foo() in quotes.

您需要将 foo() 放在引号中。

<input ui-keypress="{enter: 'foo()'}">

<input ui-keypress="{enter: 'foo()'}">

回答by Ben Lesh

You could easily just roll your own keypress directive

您可以轻松地推出自己的按键指令

Here's a plunker to demo

这是一个演示的plunker

And the code:

和代码:

app.directive('zKeypress', function(){
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('keypress', function(){
        scope.$apply(function(s) {
          s.$eval(attr.zKeypress);
        });
      });
    }
  };
});

HTML

HTML

<input type="text" z-keypress="foo()"/>