Angular js使用ng-change停止先前的http请求

时间:2014-03-03 08:22:25

标签: angularjs

尝试使用角度js实现搜索字段。

每当输入值发生变化时,它都会调用一个方法来获取查询结果。

然而它非常慢,因为对于每个char,它将调用该方法一次。我的输入搜索框如下

<input type="text" name="term" ng-model="term" ng-change="run_filter()"/>

我的功能

$scope.do_filter = function() {
    $scope.items = [];
    var canceler;
    term = $scope.term;
    if (canceler) canceler.resolve();
    canceler = $q.defer();
    $http({
        method: 'GET',
        url: '/search/do_search',
        params: {
            term: term
        },
        timeout: canceler.promise
    }).success(function(result) {
        if (result.items != null) {
            $scope.items = result.items;
            $scope.success = true;
        } else {
            $scope.success = false;
        }
        $scope.loading = false;
    });
}

但它似乎没有用。当我查看网络时,第一个请求在提交第二个请求时不会被取消。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

看看@Doug R的这个令人敬畏的指令,它增加了ng-change的延迟。

这完全挽救了我的一天,因为我的办公室里有一些非常快速的打字机。 这只会在一定数量的打字不活动后触发(300 - 500ms是一个很好的值开始)

Delayed ng-change

另一种方法是对ng-blur做出反应或强制用户按RETURN更新列表。