我正在使用ng-repeat
来创建一堆输入。 ng-repeat
循环遍历数组以了解要生成多少输入。当我单击一个按钮并将新输入推送到ng-repeat
数组时,会出现问题,这会更新视图并显示新输入。但是,我希望获得这一新输入的重点。我怎样才能做到这一点?这是我目前的代码,
JS控制器
app.controller('setCtrl', ['$scope', function($scope) {
$scope.inputs = [];
var inputCounter = 7;
for(var i = 1; i <= 7; i++) $scope.inputs.push( {counter: i, first: '', second: ''} );
// Function to add new input and then gain focus of new input
$scope.addInput = function() {
$scope.inputs.push( {counter: ++inputCounter, first: '', second: ''} );
var focus = "#input" + inputCounter;
$(focus).focus();
}
}]);
HTML / ng-repeat
<div ng-repeat="input in inputs" class="col-xs-12" style="padding-top:12px;">
<div class="col-xs-6 input-wrapper-left">
<div class="input-counter">
{{input.counter}}
</div>
<div id="input{{input.counter}}" class="input-input input-left" contenteditable>
</div>
</div>
</div>
目前,上面的代码会创建新输入,但不会对其进行关注。
答案 0 :(得分:2)
有两种解决方案,您可以使用第一种或第二种方法,但是需要在ng-repeat中添加动画。 please check this ng-repeat animation complete callback to understand how you can use this。基本上在回调电话element.focus()
方法1:
Codepen:http://codepen.io/anon/pen/meJRqV?editors=101
$scope.addInput = function()
{
$scope.inputs.push( {counter: ++inputCounter, first: '', second: ''} );
$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);
}
方法2:
Codepen:http://codepen.io/ev-tt/pen/BNXBmd?editors=101
.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();
});
});
}
};
});
此问题已经回答,请查看以下链接: