Gary Johnson Gary Johnson - 5 months ago 76
AngularJS Question

Focus a dynamically created input using ng-repeat - AngularJS

I am using

ng-repeat
to create a bunch of inputs. The
ng-repeat
loops through an array to know how many inputs to produce. The problem comes when I click a button and it pushes a new input into the
ng-repeat
array, this updates the view and a new input is visible. However, I want to gain focus of this new input. How can I do this? Here is my current code,

JS Controller

app.controller('setCtrl', ['$scope', function($scope) {

$scope.inputs = [];
var inputCounter = 7;
for(var i = 1; i <= 7; i++) $scope.inputs.push( {counter: i, first: '', second: ''} );

// Function to add new input and then gain focus of new input
$scope.addInput = function() {
$scope.inputs.push( {counter: ++inputCounter, first: '', second: ''} );
var focus = "#input" + inputCounter;
$(focus).focus();
}

}]);


HTML / ng-repeat

<div ng-repeat="input in inputs" class="col-xs-12" style="padding-top:12px;">
<div class="col-xs-6 input-wrapper-left">
<div class="input-counter">
{{input.counter}}
</div>
<div id="input{{input.counter}}" class="input-input input-left" contenteditable>
</div>
</div>
</div>


Currently, the above code creates the new input but it will not focus it.

Answer

There are two solutions for it, You can use the the first one or the second approach however it will require to add animation to your ng-repeat. please check this ng-repeat animation complete callback to understand how you can use this. Basically in callback call element.focus()

Method1:

Codepen: http://codepen.io/anon/pen/meJRqV?editors=101

$scope.addInput = function()
{
    $scope.inputs.push( {counter: ++inputCounter, first: '', second: ''} );

    $timeout(function()
    {
        // have to do this in a $timemout because
        // we want it to happen after the view is updated
       // with the newly added input
       angular.element(document.querySelectorAll('input'))
       .eq(-1)[0]
       .focus();
    }, 0);
}

Method 2:

Codepen: http://codepen.io/ev-tt/pen/BNXBmd?editors=101

.animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
      element.hide().show(100, function(){
        var scope = element.scope();
        scope.$evalAsync(function(){ 
          element.find(':last')[0].focus();
        }); 
      });
    }
  };
});

This Question is already answered please check out the links below:

1: http://stackoverflow.com/a/32162684/4578345

2: http://stackoverflow.com/a/32445706/4578345

Comments