Angular——把焦点放在动态创建的输入字段上

Angular - Give focus to a dynamically created input field

本文关键字:输入 创建 字段 焦点 Angular 动态      更新时间:2023-09-26

如何为新创建的字段添加焦点?参见目前的示例:http://jsfiddle.net/aERwc/165/

$scope.addField = function() {console.log('hi');
    $scope.fields[$scope.keyToAdd] = $scope.valueToAdd;
    $scope.setFieldKeys();
    $scope.keyToAdd = '';
    $scope.valueToAdd = '';
}

你可以使用这种方法,但是它需要在你的ng-repeat中添加动画。参见ng-repeat animation complete callback

基本上在回调调用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

对我来说,这似乎是最简单的方法:

代码

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

就我个人而言,我会使用jQuery,使代码更简单:

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

代替:

angular
  .element(document.querySelectorAll('input'))
  .eq(-1)[0]
  .focus()
;