2014-06-05 101 views
0

我正在嘗試創建一個可以「控制」兩個輸入框的directive(在使用ng-repeat創建的頁面上會有幾個這樣的指令)。我無法找到解決方案的功能是focus在兩個輸入字段之間切換焦點的指令

輸入框需要在每個指令之間切換它們之間的焦點(例如,一旦我選擇一個輸入框並按下回車鍵,焦點需要轉到它的「兄弟」輸入,然後按回車,焦點回到第一個輸入等等)。除非我在另一個指令中選擇另一個輸入,否則焦點永遠不會留下指令(即,兩個輸入框中的一個)。

這種行爲有沒有優雅的AngularJS解決方案?或者,如果沒有,是否有解決方案不涉及jQuery?

回答

0

你可以這樣做的一種方法是通過綁定keypress上的聽衆,這將會發生$broadcast事件。相同的指令可以監聽該事件,匹配以確保它不是在focus之前廣播事件的那個元素。

.directive('myDirective', function(){ 
    return { 
    scope: true, // necessary for use with ng-repeat 
    link: function(scope, elem, attrs) { 
     scope.$on('enter', function($event, argElem){ 
     if (elem !== argElem) elem[0].focus(); 
     }); 
     elem.on('keypress', function($event){ 
     if ($event.keyCode === 13) { 
      scope.$parent.$broadcast('enter', elem); 
     } 
     }); 
    } 
    } 
}) 

注:從原始響應更新,以便與NG-重複使用

Demo

0

ASSOCIATED SAMPLE with ng-repeat usage

您可以創建一個指令,將接受該元素的id您可以在按下回車鍵時進行對焦。只需使用document.getElementBy$document[0].getElementById(用於測試目的)來獲取要聚焦的元素。將事件keypress綁定到您的指令的當前元素上下文,並在按Enter鍵時觸發元素焦點。

例如

JAVSCRIPT

.directive('simpleNextFocus', function(/*$document*/) { 
    return function(scope, elem, attr) { 
    if(attr.simpleNextFocus) { 
     elem.on('keydown', function(e) { 
      if(e.keyCode == 13) { 
      // $document[0].getElementById(attr.simpleNextFocus).focus(); 
      document.getElementById(attr.simpleNextFocus).focus(); 
      } 
     }); 
    } 
    }; 
}) 

HTML

<input type="text" id="input-1" simple-next-focus="input-2"> 
<input type="text" id="input-2" simple-next-focus="input-1">