ng-repeat 和 focus 输入

ng-repeat and focus inputs

我有一个由 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-repeat :

   <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>

它对我不起作用 - 单击按钮根本不会聚焦输入。

谢谢

您必须将事件绑定到一个已经存在的元素。

<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();
});

在 angular 中,您可以借助按钮上的 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