Change focus to input on a key event in AngularJS

后端 未结 3 1579
有刺的猬
有刺的猬 2021-02-03 11:49

Test case: http://jsbin.com/ahugeg/4/edit (Slightly long)

In the above test case, I have three input elements, generated by ng-repeat directive. My intentio

3条回答
  •  日久生厌
    2021-02-03 12:25

    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:

    
        
    
    

    Controller:

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

    Directive:

    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();
              }
            }
          });
        }
      };
    });
    

提交回复
热议问题