var four = function() {
$scope.text += '4';
}
var five = function() {
$scope.text += '5';
}
$scope.text = '1';
$timeout(function () {
$scope.text += '2'
});
$timeout($scope.text += '3');
$timeout($scope.$eval(four));
$timeout(five);
结果:13425
根据调用顺序,结果应该是12345。 下面的行会立即执行:
$timeout($scope.text += '3');
$timeout($scope.$eval(four));
如果像下面这样添加时间参数,时间将被忽略。
$timeout($scope.text += '3', 1000);
$timeout($scope.$eval(four), 1000);
最佳答案
$timeout($scope.text += '3');
这一行 $scope.text += '3'
不是一个函数,而是一个表达式。所以它将在 $scope.text = '1';
之后执行。
要延迟一个语句,您需要用一个函数包装该语句并将其传递给 $timeout
或 setTimeout
。你不能推迟声明。
将 $timeout($scope.text += '3');
替换为 $timeout(function(){$scope.text += '3'})
。
您将获得输出 14235
。
$scope.$eval()
同步计算函数或表达式
4
将在 235
之前添加。
将其更改为
$timeout(function(){$scope.$eval(four)})
将得到预期的输出 12345
关于javascript - AngularJS $timeout 调用函数与匿名函数与表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40805622/