微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何延迟AngularJS即时搜索?

我是新的AngularJS,我有一个性能问题,我似乎不能解决我有即时搜索,但它有点滞后,因为它开始搜索每个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在内部这样做,阅读文档和其他主题在这里,我找不到具体的答案。

我会感激任何指针,如何我可以延迟即时搜索
谢谢。

(有关Angular 1.3解决方案,请参阅以下答案。)

这里的问题是,搜索将在每次模型更改时执行,这是每个输入上的keyup操作。

将有更干净的方法来做到这一点,但可能最简单的方法是切换绑定,以便你有一个$ scope属性定义在您的控制器内您的过滤器操作。这样你可以控制$ scope变量的更新频率。这样的东西:

JS:

var App = angular.module('App',$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>

原文地址:https://www.jb51.cc/angularjs/147357.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐