Angular - 将焦点放在动态创建的输入字段上

时间:2015-08-23 02:32:03

标签: javascript angularjs

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用此方法,但需要在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();
        }); 
      });
    }
  };
});

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

答案 1 :(得分:1)

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

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

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

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

而不是:

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