Gary Johnson Gary Johnson - 1 year ago 178
AngularJS Question

Focus a dynamically created input using ng-repeat - AngularJS

I am using

to create a bunch of inputs. The
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
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;


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">
<div id="input{{input.counter}}" class="input-input input-left" contenteditable>

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

Answer Source

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



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

        // have to do this in a $timemout because
        // we want it to happen after the view is updated
       // with the newly added input
    }, 0);

Method 2:


.animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
      element.hide().show(100, function(){
        var scope = element.scope();

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



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download