Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度-为动态创建的输入字段提供焦点_Javascript_Angularjs - Fatal编程技术网

Javascript 角度-为动态创建的输入字段提供焦点

Javascript 角度-为动态创建的输入字段提供焦点,javascript,angularjs,Javascript,Angularjs,如何将焦点添加到新创建的字段? 见迄今为止的例子: 您可以使用这种方法,但是需要将动画添加到ng repeat中。看 基本上是在回调调用element.focus() 更新代码笔:对我来说,这似乎是最简单的方法: HTML <html ng-app='app'> <body ng-controller='MainController as vm'> <input ng-repeat='thing in vm.things'> <hr

如何将焦点添加到新创建的字段? 见迄今为止的例子:


您可以使用这种方法,但是需要将动画添加到ng repeat中。看

基本上是在回调调用
element.focus()


更新代码笔:

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

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>

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

$('input:last').focus();
而不是:

angular
  .element(document.querySelectorAll('input'))
  .eq(-1)[0]
  .focus()
;
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);
  };
}
$('input:last').focus();
angular
  .element(document.querySelectorAll('input'))
  .eq(-1)[0]
  .focus()
;