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