angularJs指令绑定keydown事件

时间:2017-07-16 08:09:40

标签: angularjs-directive

https://stackoverflow.com/a/15529412/4310103 我在这里看了一下这个答案,看到用这个解决方案,用户可以通过click事件将处理程序绑定到一个元素...如果我想将一个处理函数绑定到一个元素并拥有从keydown事件触发的函数。这是我能够集合的。但是预期的效果并没有呈现出来。我按下向下(40)键后尝试将UI焦点放在第二个输入上。我做错了什么?:

HTML

<body ng-app = 'angularjs-starter'>
<div ng-controller="MainCtrl">
<div class="element-wrapper" ng-repeat="element in elements">
<div class="first-wrapper">
 <button class="button">{{element.name}}</button>   
  </div>
  <div class="second-wrapper">
    <input type="text" focus-input value="{{element.value}}">   
  </div>
</div>
</div>
</body>    


AngularJs
    var app = angular.module('angularjs-starter', []);
app.js
    app.directive('focusInput', function($timeout) {
      return {
        link: function(scope, element, attrs) {
          element.bind('keydown', function(event) {
            if (event.which == 40)
              $timeout(function() {
                element.parent().parent().find('input')[1].focus();
              });
            });
          }
      };
    });
app.controller('MainCtrl', function($scope) {
  $scope.elements = [ {name: 'n1', value: 1}, {name: 'n2', value: 2}];
});   

https://jsfiddle.net/fcjy69ho/3/

我很高兴地说我解决了自己的问题。我只是在元素上设置了一个id,并将所有元素缓存到我可以引用的数组中,然后使用document.activeElement来确定是否应该向上或向下切换。

HTML

<body ng-app = 'angularjs-starter'>
<div ng-controller="MainCtrl">
<div class="element-wrapper" ng-repeat="element in elements">
  <div class="first-wrapper">
    <button class="button">{{element.name}}</button>   
  </div>
  <div class="second-wrapper">
    <input id = 'this_input' type="text" value="{{element.value}}" focus-input='this_input' tabIndex="0"> 
  </div>
</div>
</div>
</body>

AngularJS
var app = angular.module('angularjs-starter', []);

app.directive('focusInput', function($timeout) {
return {
link: function(scope, element, attrs) { 
  element.bind('keydown', function(event) {
        var otherElement = document.querySelectorAll('#' + attrs.focusInput);  
        if (event.which == 40 && otherElement[0] === document.activeElement){
             console.log("this kinda works.");
             $timeout(function(){
               otherElement[1].focus();
             }).catch(function(err){
               console.log(err);
             });
         }
      else if (event.which == 38 && otherElement[1] === document.activeElement){
          $timeout(function(){
            console.log('We really got this to work');
            otherElement[0].focus();
          }).catch(function(err){
            console.log(err);
          });
      }
      else 
          console.log('Not the key we are looking for.');
  });
}
}  
});

app.controller('MainCtrl', function($scope) {
$scope.elements = [ {name: 'n1', value: 1}, {name: 'n2', value: 2}];
});

0 个答案:

没有答案