[英]Angular - Give focus to a dynamically created input field
如何將焦點添加到新創建的字段? 見到目前為止的例子: 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動畫完成回調
基本上在回調中調用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?編輯= 101
對我來說,這似乎是最簡單的方法:
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()
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.