2016-05-30 105 views
0

我有一個由ng-repeat生成的按鈕和輸入列表,我想要以下功能:當我點擊一個按鈕時,它將重點關注以下輸入。ng-repeat和焦點輸入

如果我使用:

<div> 
     <button class="btn btn-sm chat-option chat-option-add but-0" style="padding: 0px;border-radius: 50%;"></button> 
     <input type="text" class="input-0" style="color:black;"> 
    </div> 

    <div> 
     <button class="btn btn-sm chat-option chat-option-add but-1" style="padding: 0px;border-radius: 50%;"></button> 
     <input type="text" class="input-1" style="color:black;"> 
    </div>`enter code here` 
<script> 
    $('.but-0').click(function() { 
     $('.input-0').focus(); 
    }); 
    </script> 

    <script> 
    $('.but-1').click(function() { 
     $('.input-1').focus(); 
    }); 
    </script> 

它工作正常。 但如果我想使用NG重複使用這些腳本:

<div ng-repeat="f in testFocus"> 
      <button class="btn btn-sm chat-option chat-option-add but-{{$index}}" style="padding: 0px;border-radius: 50%;"></button> 
      <input type="text" class="input-{{$index}}" style="color:black;"> 

     </div> 

它不爲我工作 - 點擊按鈕不會在所有關注的輸入。

謝謝

回答

1

您必須將事件綁定到已存在的元素。

<button class="btn btn-sm chat-option chat-option-add but-{{$index}}" style="padding: 0px;border-radius: 50%;">button</button> 
<input type="text" class="input-{{$index}}" style="color:black;" /> 
$(document).on('click', '.but-0', function() { 
    $('.input-0').focus(); 
}); 

$(document).on('click', '.but-1', function() { 
    $('.input-1').focus(); 
}); 

在角可以通過利用ng-click幫助按鈕做的更優雅。

<button class="btn btn-sm chat-option chat-option-add" ng-click="buttonClicked($index)" style="padding: 0px;border-radius: 50%;">button</button> 
<input type="text" class="input-{{$index}}" style="color:black;" /> 
$scope.buttonClicked = function($index) { 
    $('.input-'+ $index).focus(); 
} 

看到這個DEMO

+0

謝謝敵我的答案,它工作正常這種方式,但遇到問題即時如果我使用NG-表演。我不明白爲什麼它會傷害綁定。 user6315833

+0

使用'$ timeout'來執行這段代碼'$('。input - '+ $ index).focus已移除。看到這[plunker](http://plnkr.co/edit/JLJLlzcOoSgeZ5TmPFHK?p=preview)。順便說一下,當'ng-show'爲true時,您還可以使用指令來對元素進行聚焦。對於這一個,看到這[後](http://stackoverflow.com/questions/24415168/setting-focus-on-an-input-field-after-ng-show)。 – Saad