如何把AngularJS即时搜索延迟? [英] How to put a delay on AngularJS instant search?

查看:685
本文介绍了如何把AngularJS即时搜索延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来AngularJS,我有性能问题,我似乎无法应对。我有瞬间的搜索,但它有点laggy,因为它开始在每个搜索的keyup()。

I am new to AngularJS, and I have a performance issue that I can't seem to address. I have instant search but it's somewhat laggy, since it starts searching on each keyup().

JS:

var App = angular.module('App', []);

App.controller('DisplayController', function($scope, $http) {
$http.get('data.json').then(function(result){
    $scope.entries = result.data;
});
});

HTML

<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:searchText">
<span>{{entry.content}}</span>
</div>

JSON数据甚至不是很大,只有300KB,我想我需要做到的是把对搜索〜1秒的延迟,以等待用户来完成,而不是在表演动作打字,每次击键。 AngularJS做到这一点内部,和阅读的文档在这里和其他主题后,我无法找到一个明确的答案。

The JSON data isn't even that large, 300KB only, I think what I need to accomplish is to put a delay of ~1 sec on the search to wait for the user to finish typing, instead of performing the action on each keystroke. AngularJS does this internally, and after reading docs and other topics on here I couldn't find a specific answer.

我想AP preciate我如何能延缓即时搜索任何指针。
谢谢你。

I would appreciate any pointers on how I can delay the instant search. Thanks.

推荐答案

(请参见下面回答一个角1.3解决方案。)

(See answer below for a Angular 1.3 solution.)

这里的问题是,搜索将执行每次模式的转变,这是一个输入的每个动作KEYUP

The issue here is that the search will execute every time the model changes, which is every keyup action on an input.

有将是更清洁的方式来做到这一点,但可能是最简单的方法是将切换的结合,你有哪些过滤器运行的控制器中定义的$ scope属性。这样,你可以控制的范围$变量是如何经常​​更新。事情是这样的:

There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:

JS:

var App = angular.module('App', []);

App.controller('DisplayController', function($scope, $http, $timeout) {
    $http.get('data.json').then(function(result){
        $scope.entries = result.data;
    });

    // This is what you will bind the filter to
    $scope.filterText = '';

    // Instantiate these variables outside the watch
    var tempFilterText = '',
        filterTextTimeout;
    $scope.$watch('searchText', function (val) {
        if (filterTextTimeout) $timeout.cancel(filterTextTimeout);

        tempFilterText = val;
        filterTextTimeout = $timeout(function() {
            $scope.filterText = tempFilterText;
        }, 250); // delay 250 ms
    })
});

HTML

<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
    <span>{{entry.content}}</span>
</div>

这篇关于如何把AngularJS即时搜索延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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