2014-10-09 72 views
5

我看了多個線程,並嘗試了各種解決方案。坦率地說,我認爲我正在失去理智。使用回車鍵作爲選項卡只使用angularjs和jqlite

我有一個ng-repeat輸入。所有需要發生的事情是,當用戶按下Enter時,它應該將焦點轉移到下一個輸入,基本上模擬標籤鍵功能。

的代碼(不完全): HTML:

<body ng-app="ap" ng-controller="con"> 
<table> 
    <tr> 
     <th>Name</th> 
     <th>Age</th> 
    </tr> 
    <tr ng-repeat='person in persons'> 
     <td> 
      <input type='text' 
       name="personName" 
       ng-model="person.name" 
      /> 
     </td> 
     <td> 
      <input type='number' 
       name="personName" 
       ng-model="person.age" 
       enter-as-tab 
      /> 
     </td> 
    </tr> 
</table> 

JS:

var app = angular.module("ap", []); 

app.controller("con", function ($scope) { 

    $scope.persons = [ 
     { name: 'Susan', age: 1 }, 
     { name: 'Peter', age: 1 }, 
     { name: 'Jack', age: 2 } 
    ]; 
}); 

app.directive('enterAsTab', function() { 
    return function (scope, element, attrs) { 
     element.bind("keydown keypress", function (event) { 
      if(event.which === 13) { 
       event.preventDefault(); 
       // Go to next age input       
      } 
     }); 
    }; 
}); 

下面是對小提琴的鏈接:fiddle

+0

您已經嘗試了哪些解決方案? – AlexFoxGill 2014-10-09 12:54:04

+0

我從小提琴中刪除了代碼,所以我沒有對它們的引用,但這基本上是我想實現的:[link](http://stackoverflow.com/questions/23430830/keyboard - 導航功能於angularjs表) – avn 2014-10-09 12:55:31

回答

10

好了,我弄清楚了。畢竟這並不困難。剛剛陷入了「不要以爲使用Angular時jQuery」的思維方式。

這裏是我實現的指令:

app.directive('enterAsTab', function() { 
    return function (scope, element, attrs) { 
     element.bind("keydown keypress", function (event) { 
      if(event.which === 13) { 
       event.preventDefault(); 
       var elementToFocus = element.next('tr').find('input')[1]; 
       if(angular.isDefined(elementToFocus)) 
        elementToFocus.focus(); 
      } 
     }); 
    }; 
}); 

這裏是鏈接到工作小提琴:enter-as-tab

0

從@ AVN的解決方案開始,我做了一些改動,以遞歸查找和焦點移到下一個輸入文本或輸入號碼,但只限於該值有效或發送表單。設計用於ionic表格,但可以適用於任何角度形式:

app.directive('enterAsTab', function() { 
    return { 
    restrict: 'A', 
    require: '^ngModel', 
    link: function (scope, element, attrs, ctrl) { 
     element.bind("keydown keypress", function (event) { 

     function isKeyEnterAndValid(){ 
      return event.which === 13 && ctrl.$valid; 
     } 

     function nextItem(div, tag){ 
      var next = div.next(tag); 
      if (!next) return nextItem(div, 'label'); 
      return next; 
     } 

     function isTypeTextOrNumber(input){ 
      return ['text', 'number'].indexOf(input.attr('type')) === -1; 
     } 

     function findInput(div){ 
      var next = nextItem(div, 'div'); 
      if (!next) return; 
      var input = next.find('input'); 
      if (!input || isTypeTextOrNumber(input)){ 
      return findInput(next); 
      } 
      return input[0]; 
     } 

     if(isKeyEnterAndValid()) { 
      var nextInput = findInput(element.parent()); 
      if(angular.isDefined(nextInput)){ 
      event.preventDefault(); 
      nextInput.focus(); 
      } 
     } 

     }); 
    } 
    }; 
});