我有一个似乎无法解决的性能问题。我有一个即时搜索,但它有点滞后,因为它开始搜索每个 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),只需在模型上添加一个去抖选项即可。
<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">
更新了插件:
http://plnkr.co/edit/4V13gK
有关 ngModelOptions 的文档:
https://docs.angularjs.org/api/ng/directive/ngModelOptions
旧方法:
这是另一种方法,除了 Angular 本身之外没有任何依赖项。
您需要设置一个超时并将当前字符串与过去的版本进行比较,如果两者相同,则执行搜索。
$scope.$watch('searchStr', function (tmpStr)
{
if (!tmpStr || tmpStr.length == 0)
return 0;
$timeout(function() {
// if searchStr is still the same..
// go ahead and retrieve the data
if (tmpStr === $scope.searchStr)
{
$http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
// update the textarea
$scope.responseData = data.res;
});
}
}, 1000);
});
这会进入你的视野:
<input type="text" data-ng-model="searchStr">
<textarea> {{responseData}} </textarea>
强制性的骗子: http://plnkr.co/dAPmwf
关于search - 如何延迟 AngularJS 即时搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15304562/