改变焦点输入在AngularJS的关键事件 [英] Change focus to input on a key event in AngularJS

查看:112
本文介绍了改变焦点输入在AngularJS的关键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试案例: http://jsbin.com/ahugeg/4/edit (略长)

在上面的测试情况下,我有三个输入元素,由生成的NG-重复指令。我在这个测试用例意图是,击中的这些输入中的一个的向上/向下箭头应在相应的方向上移动焦点到输入,如果有在该方向提供一个输入

In the above test case, I have three input elements, generated by ng-repeat directive. My intention in this test case, is that hitting the up/down arrows in one of these inputs should move focus to the input in the corresponding direction, if there is an input available in that direction.

我是新来AngularJS,所以我可能会丢失一些简单的方法来做到这一点。无论如何,我定义了两个新指令(上了上向下),来处理上下活动和我调用 $ scope.focusNext $ scope.focus $ p $光伏方法,传递正确的条目,相对于后者的焦点应该移动。这是我在哪里卡住了。

I am new to AngularJS, so I might be missing on some straightforward way to do this. Anyway, I defined two new directives (on-up and on-down), to handle the up and down events and am calling the $scope.focusNext and $scope.focusPrev methods, passing the correct entry, relative to which the focus should move. This is where I am stuck.

我知道这是不是的角路的处理在控制器DOM元素,但我不能怎么看的焦点的可以被看作是一个属性/模型的属性。我甚至想到有一个单独的 $ scope.focusedEntry ,但我应该的关于该属性的变化?即使我做,我发现变化,我怎么能访问与我想集中条目的输入元素?

I know it is not the angular-way to deal with DOM elements in controllers, but I can't see how the focus can be seen as an attribute/property of a model. I even thought of having a separate $scope.focusedEntry, but then should I watch for changes on that property? Even if I do and I detect changes, how can I access the input element corresponding to the entry I want focused?

在这个应该怎么做都非常AP preciated任何帮助。

Any help on how this should be done are very much appreciated.

推荐答案

我刚写了这件事,并测试它简单 - 它你想要做什么,而无需在控制器中的所有额外的杂波和在HTML中。看到它的工作这里

I just wrote this up and tested it briefly - it does what you want without all the extra clutter in your controller and in the HTML. See it working here.

HTML

<body ng-controller="Ctrl">
    <input ng-repeat="entry in entries" value="{{entry}}" key-focus />
</body>

控制器:

function Ctrl($scope) {
  $scope.entries = [ 'apple', 'ball', 'cow' ];
}

指令:

app.directive('keyFocus', function() {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      elem.bind('keyup', function (e) {
        // up arrow
        if (e.keyCode == 38) {
          if(!scope.$first) {
            elem[0].previousElementSibling.focus();
          }
        }
        // down arrow
        else if (e.keyCode == 40) {
          if(!scope.$last) {
            elem[0].nextElementSibling.focus();
          }
        }
      });
    }
  };
});

这篇关于改变焦点输入在AngularJS的关键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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