如何在延迟 2 秒后触发 $watch 或执行范围订阅 属性 的最后一个条件?

How to trigger $watch after 2s delay or execute the last condition of a subscribed property of a scope?

我有一个触发监视的搜索输入,然后向数据库发送一个新请求

var timeoutPromise;
var delayInMs = 2000;
$scope.$watch('search', function() {
    $timeout.cancel(timeoutPromise); 
    timeoutPromise = $timeout(function(){ 
        $scope.nameFilter = '&filter[]=Name,cs,' + $scope.search;
        $scope.updatePage(1);
    });
}, delayInMs);

延迟的主要目标是 watch 不是在搜索输入中的每个新字符上触发,而是在修改至少几个字母后触发。

不幸的是,这个手表只是把所有请求放在一个队列中,并在延迟之后执行所有请求。

请帮帮我

更新

如果您想在触发 ng-change 之前等待几毫秒,您可以使用 George 建议的 ng-model-options

<input type="search" ng-model="search" ng-change="searchFunction()" ng-model-options="{ debounce: 2000 }" />

如果你坚持按照你写的方式去做,你可以使用下面的代码

您不需要 $scope.$watch,因为 angular 会自动更新搜索 属性。所以用$timeout延迟执行

var timeoutPromise;
var delayInMs = 2000;
timeoutPromise = $timeout(function() {
        $timeout.cancel(timeoutPromise);
        $scope.nameFilter = '&filter[]=Name,cs,' + $scope.search;
        $scope.updatePage(1);
}, delayInMs);

Angular 内置了类似这样的东西,只是方式略有不同。 我建议这样做,延迟更改的部分在 ng-model-options

JS

$scope.search = "";

$scope.searchFunction = function(){ 
    $scope.nameFilter = '&filter[]=Name,cs,' + $scope.search;
    $scope.updatePage(1);
}

HTML

<input type="text" ng-model="search" ng-change="searchFunction()" ng-model-options="{ debounce: 2000 }" />

您可能还想利用输入类型 search

在您的代码中,delayInMs$watch 的第三个参数,而不是 $timeout 的参数。以下应该可以正常工作:

var timeoutPromise;
var delayInMs = 2000;
$scope.$watch('search', function() {
    $timeout.cancel(timeoutPromise); 
    timeoutPromise = $timeout(function(){ 
        $scope.nameFilter = '&filter[]=Name,cs,' + $scope.search;
        $scope.updatePage(1);
    }, delayInMs);
});