2016-05-30 104 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