如何延迟AngularJS即时搜索?
发布时间:2020-12-17 09:20:28 所属栏目:安全 来源:网络整理
导读:我是新的AngularJS,我有一个性能问题,我似乎不能解决。我有即时搜索,但它有点滞后,因为它开始搜索每个keyup()。 JS: var App = angular.module('App',[]);App.controller('DisplayController',function($scope,$http) {$http.get('data.json').then(fun
我是新的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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |