我有一个似乎无法解决的性能问题。我有一个即时搜索,但它有点滞后,因为它开始搜索每个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 在内部执行此操作,在阅读此处的文档和其他主题后,我找不到具体的答案。
如果有人告诉我如何延迟即时搜索,我将不胜感激。
UPDATE
现在比以往任何时候都更容易(Angular 1.3),只需在模型上添加一个去抖选项即可。
<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">
更新后的笨蛋:
http://plnkr.co/edit/4V13gK http://plnkr.co/edit/4V13gK
有关 ngModelOptions 的文档:
https://docs.angularjs.org/api/ng/directive/ngModelOptions https://docs.angularjs.org/api/ng/directive/ngModelOptions
旧方法:
这是另一种方法,除了角度本身之外没有任何依赖性。
您需要设置一个超时并将当前字符串与过去的版本进行比较,如果两者相同,则执行搜索。
$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 http://plnkr.co/dAPmwf
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)