如何将焦点添加到新创建的字段? 请参见目前为止的示例:http://jsfiddle.net/aERwc/165/
$scope.addField = function() {console.log('hi');
$scope.fields[$scope.keyToAdd] = $scope.valueToAdd;
$scope.setFieldKeys();
$scope.keyToAdd = '';
$scope.valueToAdd = '';
}
答案 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();
});
});
}
};
});
答案 1 :(得分:1)
对我来说,这似乎是最简单的方法:
<强> 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()
;