Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Give focus to a dynamically created input field

How would I add focus to the newly created field? See example thus far: http://jsfiddle.net/aERwc/165/

$scope.addField = function() {console.log('hi');
    $scope.fields[$scope.keyToAdd] = $scope.valueToAdd;
    $scope.setFieldKeys();
    $scope.keyToAdd = '';
    $scope.valueToAdd = '';
}
like image 334
user994694 Avatar asked Sep 26 '22 23:09

user994694


2 Answers

You can use this approach however it will require to add animation to your ng-repeat. see ng-repeat animation complete callback

Basically in callback call element.focus()

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

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

like image 68
vittore Avatar answered Sep 30 '22 03:09

vittore


To me, this seems like the simplest way to do it:

Code Pen

HTML

<html ng-app='app'>
  <body ng-controller='MainController as vm'>
    <input ng-repeat='thing in vm.things'>
    <hr />
    <button ng-click='vm.addThing()'>Add Thing</button>
  </body>
</html>

JS

angular
  .module('app', [])
  .controller('MainController', MainController)
;

function MainController($timeout) {
  var vm = this;
  vm.things = [{}];
  vm.addThing = function() {
    vm.things.push({});
    $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);
  };
}

Personally, I would actually use jQuery and make the code even simpler:

$('input:last').focus();

Instead of:

angular
  .element(document.querySelectorAll('input'))
  .eq(-1)[0]
  .focus()
;
like image 20
Adam Zerner Avatar answered Sep 30 '22 04:09

Adam Zerner