如何在正确的时间在一个角度改变后选择一个输入文字? [英] How to select text in an input after a change in Angular at the right time?
问题描述
我有一个输入框。当文本的变化,我需要选择文本。据我所知,有许多事件回事,我需要等待他们完成。我把超时和它的作品。不过,我不想依靠一定的时间。有什么办法如何角时完成更改文本选择的文本?
I have an input box. When the text changes, I need to select the text. I understand that there are many events going on and I need to wait for them to finish. I put in a timeout and it works. However I don't want to rely on a constant time. Is there any way how to select the text when Angular is finished changing the text?
示例HTML:
<input type="text" value="{{txt}}">
<button ng-click="select()">Press</button>
例如JS:
angular.module('MyApp', []).controller('MyCtrl', function ($scope, $interval) {
$scope.txt = "Hello World";
$scope.select = function () {
$scope.txt = "Bye World";
// doesn't work, too early
document.querySelector("input").setSelectionRange(0, 4);
// works
$interval(function () {
document.querySelector("input").setSelectionRange(0, 4);
}, 10, 1);
}
});
修改:从它看起来像使用超时(即使是0延迟)的答案是一种常见的做法,但问题是这是否会保证选择发生角完成更新后的文本。
EDIT: From the answers it looks like using timeouts (even with 0 delay) is a common practice, but the question remains whether this will guarantee that the selection happens after Angular finishes updating the text.
推荐答案
您可以用$暂停时以0延迟用于这一目的。
You can use $timeout with 0 delay for this purpose.
$timeout(function(){
document.querySelector("input").setSelectionRange(0, 4);
});
角度变化在明年 $消化
周期的DOM,它是非常快,但它不会,只要你运行提供 $ scope.x = ??
。通常我们会使用 $超时
来等待在这种情况下。
Angular changes the DOM in next $digest
cycle, it is extremely fast, but it won't be available as soon as you run $scope.x = ??
. Normally we would use $timeout
to "wait" in this case.
这篇关于如何在正确的时间在一个角度改变后选择一个输入文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!