用于文本输入的AngularJS指令:关注Enter上的下一个输入

时间:2014-10-08 10:36:35

标签: javascript angularjs

我想为AngularJS实现这样的指令:如果在输入[text]中使用,在点击输入时焦点将转移到下一个输入。什么是实现这一目标的最佳方式?

我有一个非常大的表格,并想实现一种快速浏览字段的方法。

3 个答案:

答案 0 :(得分:4)

选中 FIDDLE

AngularJS中有ngKeypress指令,您可以在here中阅读更多内容。

如果你提到的表单是静态的,那么最简单的方法就是传递下一个输入的id(或者我的例子中的索引)。由您决定如何提供ID,您可以传递整个id或索引。

<input type="text" ng-model="field1" id="f_1"
       ng-keypress="keypressHandler($event, 2)"/>
<br/>
<input type="text" ng-model="field2" id="f_2" 
       ng-keypress="keypressHandler($event, 3)"/>
<br/>

然后在你的控制器中,如果输入了key,则按给定的id获取元素,然后将其聚焦。

$scope.keypressHandler = function(event, nextIdx){
    if(event.keyCode == 13){
        angular.element(
            document.querySelector('#f_'+nextIdx))[0].focus();

    }
}

正如您所看到的,您可以通过传递$ index而不是硬编码数字并动态创建ID来使用ng-repeat。

答案 1 :(得分:0)

另一种解决方案,使用此指令:

angular.module('myApp').directive("nextFocus", nextFocus);

/** Usage:
  <input next-focus id="field1">
  <input next-focus id="field2">
  <input id="field3">
  Upon pressing ENTER key the directive will switch focus to
  the next field id e.g field2
  The last field should not have next-focus directive to avoid
  focusing on non-existing element.
  Works for Web, iOS (Go button) & Android (Next button) browsers, 
**/

function nextFocus() {
  var directive = {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      elem.bind('keydown', function(e) {
        var partsId = attrs.id.match(/field(\d{1})/);
        var currentId = parseInt(partsId[1]);

        var code = e.keyCode || e.which;
        if (code === 13) {
          e.preventDefault();
          document.querySelector('#field' + (currentId + 1)).focus();
        }
      });
    }
  };
  return directive;

}

相关:angularjs move focus to next control on enter

答案 2 :(得分:0)

创建自定义指令:

.directive('nextOnEnter', function () {
    return {
        restrict: 'A',
        link: function ($scope, selem, attrs) {
            selem.bind('keydown', function (e) {
                var code = e.keyCode || e.which;
                if (code === 13) {
                    e.preventDefault();
                    var pageElems = document.querySelectorAll('input, select, textarea'),
                        elem = e.srcElement
                        focusNext = false,
                        len = pageElems.length;
                    for (var i = 0; i < len; i++) {
                        var pe = pageElems[i];
                        if (focusNext) {
                            if (pe.style.display !== 'none') {
                                pe.focus();
                                break;
                            }
                        } else if (pe === e.srcElement) {
                            focusNext = true;
                        }
                    }
                }
            });
        }
    }
})

来源:https://stackoverflow.com/a/36960376/717267