我正在尝试创建一个 Angular 表单,在此表单中,用户键入文本时,在其下方的文本标签中显示“用户正在输入...”。
然后,它等待 200 毫秒,文本标签变为空白(“用户正在输入...”消失)。
我使用了 Angular ng-change 指令来实现。我的代码如下。
问题在于,由于某种原因,我编写的帮助方法在运行两个方法之间进行等待时出现了问题。由于某种原因,“用户正在输入...”文本无法在短暂等待后消失。
为什么会这样呢?
谢谢。
然后,它等待 200 毫秒,文本标签变为空白(“用户正在输入...”消失)。
我使用了 Angular ng-change 指令来实现。我的代码如下。
问题在于,由于某种原因,我编写的帮助方法在运行两个方法之间进行等待时出现了问题。由于某种原因,“用户正在输入...”文本无法在短暂等待后消失。
为什么会这样呢?
谢谢。
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
runTwoFunctionWithSleepBetweenThem(function (){$scope.text='user is typing...';},function (){$scope.text='';},200);
};
var runTwoFunctionWithSleepBetweenThem = function(foo1,foo2, time) {
var sleep =function (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
foo1();
sleep(time).then(() => {
foo2();
});
}
}]);
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<p>Write something in the input field:</p>
<input type="text" ng-change="myFunc()" ng-model="myValue" />
<p>{{text}}</p>
</div>
</body>
</html>
$scope.$apply
... - user4615488$scope.$apply()
以便使$scope.text
变量的更改生效。 - Titus