在 Angular 中按键绑定函数 [英] Bind function on key up in Angular

查看:25
本文介绍了在 Angular 中按键绑定函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名设计师/前端开发人员,对 Angular 几乎没有经验,所以我希望能在这里得到一些帮助.我有以下 html

如果用户在后续输入中按下 Enter 键,我想从 元素触发点击事件.我想以最简单的方式做到这一点,而无需编写单独的函数.任何有 Angular 经验的人都知道这样做的最佳方法吗?我知道我可以轻松地使用 jQuery 并执行以下操作:

$('#add-issue-field').keypress(function(e){var key = e.which;如果(键 === 13){$('#add-issue-plus').click();返回假;}});

但我想知道是否有人有更有效方法的提示.

解决方案

对此的最佳用途是指令.这是一个例子.

app.directive('checkKey', function() {返回 {限制:'A',链接:功能(范围,元素,属性){elem.bind('keyup', function(event) {if (event.keyCode === 13) {event.preventDefault();返回假;}});}}});

然后将指令添加到您的输入元素

I am a designer/front-end developer and have little to no experience with Angular, so I'm hoping to get some help here. I have the following html

<div class="dropdown">
<div class="options"></div>
  <div class="add">
    <i id="add-issue-plus" class="icon-plus" data-ng-click="addIssue($event)"></i>
    <input id="add-issue-field" data-ng-model="newIssueName" type="text" placeholder="Create a new issue"/>
  </div>
</div>

I would like to trigger the click event from the <i> element if the user presses enter while in the subsequent input. I wanted to do this the simplest way possible without writing a separate function. Anyone with Angular experience know of the best way to do this? I know I could easily use jQuery and do something like:

$('#add-issue-field').keypress(function(e){
   var key = e.which;
   if (key === 13) {
      $('#add-issue-plus').click();
        return false;
  }
 });

But I was wondering if anyone had tips for a more efficient method.

解决方案

The best use for this is a directive. Here is an example.

app.directive('checkKey', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind('keyup', function(event) {
                if (event.keyCode === 13) {
                    event.preventDefault();
                    return false;
                }
            });
        }
    }
});

And then add the directive to your input element

<input type="text" checkkey />

这篇关于在 Angular 中按键绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆