AngularJS:$ debow debounce [英] AngularJS: $watch with debounce

查看:89
本文介绍了AngularJS:$ debow debounce的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代表搜索字段的html:

I have the following html which represents a search field:

<input ng-model-options="{ debounce: 500 }" type="text" ng-model="name">

以下js:

$scope.$watch('name', function(newVal, oldVal) {
            if(newVal != oldVal) {
                $scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
            }
        });

现在,我的pageChanged函数对我的服务器进行REST调用,并返回一个基于排序和搜索信息(名称)。假设我的用户想要搜索Tom。我想避免我的应用程序进行三次休息调用(name =T,name =To,name =Tom)。

Now, my pageChanged function makes a REST call to my server and returns a list of entites based on the sort and search information (the "name"). Say that my user wants to search for a "Tom". I would like to avoid my application making three rest calls (name="T", name="To", name="Tom").

我试过这样做有去抖动,但似乎手表不能用去抖动,所以我想知道用最少的代码实现这个的最佳方法是什么?

I tried doing this with debounce, but it seems that watch doesn't work with debounce so I was wondering what would be the best way to implement this with minimal code?

推荐答案

你应该使用ng-change来代替手表。

You should be using ng-change for this sort of thing instead of wiring up a watch.

<input ng-model-options="{ debounce: 500 }" type="text" ng-model="name" ng-change="modelChanged()">

JS:

var timeout = $timeout(function(){});

$scope.modelChanged = function(){
    $timeout.cancel(timeout); //cancel the last timeout
    timeout = $timeout(function(){
        $scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
    }, 500);
};

我不熟悉去抖动,但它可能会达到同样的效果。

I'm unfamiliar with debounce, but it might achieve the same thing.

这篇关于AngularJS:$ debow debounce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆