user6315833 user6315833 - 6 months ago 26
AngularJS Question

ng-repeat and focus inputs

I have a list of buttons and inputs generated by ng-repeat, and i want the follwing functionality :
when i clicks a button it focus the following input.

if i use:

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


it works fine.
but if i want to use ng-repeat with those scripts :

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


it doesn't work for me - clicking the button does not focus the input at all.

thanks

Answer

You have to bind event to an already existing element.

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

In angular you can do it more elegantly by taking help of ng-click on the button.

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

See this DEMO

Comments