实施$范围。$手表延迟 [英] Implement a delay on $scope.$watch
问题描述
我不知道它是否可以实现在$范围。$表稍有延迟。我有一个查询服务器下面,所以我想实现一个轻微的延迟它查询服务器之前评估查询
之前。我已经注意到,如果你输入很快它就会犯糊涂,不发送正确的信息:
$范围。$表(查询功能(){
$ scope.loading = TRUE;
returnFactory.query($ scope.query)。然后(函数(返回){
$ scope.returns =回报;
$ scope.loading = FALSE;
});
});
通常我会说使用角度的$超时这种延迟,但你不能清除此超时呢。
//修改:您可以
设置超时时间,并且清除它,如果这观察家被触发快速足够多。
这样的:
VAR超时code;
VAR delayInMs = 2000;
$范围。$表(查询功能(查询){
clearTimeout(超时code); //什么都不做,如果超时alrdy完成
超时code = setTimeout的(函数(){//设置超时
$ scope.loading = TRUE;
returnFactory.query(查询)。然后(函数(返回){
$ scope.returns =回报;
$ scope.loading = FALSE;
});
},delayInMs);
});
更新感谢的Stewie
这可以通过角度的$超时来实现。
VAR timeoutPromise;
VAR delayInMs = 2000;
$范围。$表(查询功能(查询){
$ timeout.cancel(timeoutPromise); //什么都不做,如果超时alrdy完成
timeoutPromise = $超时(函数(){//设置超时
$ scope.loading = TRUE;
returnFactory.query(查询)。然后(函数(返回){
$ scope.returns =回报;
$ scope.loading = FALSE;
});
},delayInMs);
});
I was wondering whether or not it is possible to implement a slight delay on $scope.$watch. I have the following which queries the server, so I'd like to implement a slight delay before it evaluates the query
before querying the server. I've noticed that if you type to quickly it gets confused and doesn't send the correct information:
$scope.$watch("query", function () {
$scope.loading = true;
returnFactory.query($scope.query).then(function (returns) {
$scope.returns = returns;
$scope.loading = false;
});
});
Normally i'd say use angular's $timeout for this delay but you cant clear this timeout yet.
//EDIT:you can.
Set a timeout and clear it, if this watcher gets triggered fast enought.
Like this:
var timeoutCode;
var delayInMs = 2000;
$scope.$watch("query", function(query) {
clearTimeout(timeoutCode); //does nothing, if timeout alrdy done
timeoutCode = setTimeout(function(){ //Set timeout
$scope.loading = true;
returnFactory.query(query).then(function(returns) {
$scope.returns = returns;
$scope.loading = false;
});
},delayInMs);
});
UPDATE Thanks to stewie this can be achieved with angular's $timeout.
var timeoutPromise;
var delayInMs = 2000;
$scope.$watch("query", function(query) {
$timeout.cancel(timeoutPromise); //does nothing, if timeout alrdy done
timeoutPromise = $timeout(function(){ //Set timeout
$scope.loading = true;
returnFactory.query(query).then(function (returns) {
$scope.returns = returns;
$scope.loading = false;
});
},delayInMs);
});
这篇关于实施$范围。$手表延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!