Reputation: 4869
Trying to implement a search field with angular js.
Everytime the input value changes, it will call a method to fetch the query results.
However its very slow because for every char, it will call the method once. My input search box as below
<input type="text" name="term" ng-model="term" ng-change="run_filter()"/>
My function
$scope.do_filter = function() {
$scope.items = [];
var canceler;
term = $scope.term;
if (canceler) canceler.resolve();
canceler = $q.defer();
$http({
method: 'GET',
url: '/search/do_search',
params: {
term: term
},
timeout: canceler.promise
}).success(function(result) {
if (result.items != null) {
$scope.items = result.items;
$scope.success = true;
} else {
$scope.success = false;
}
$scope.loading = false;
});
}
But it doesnt seem to work. When I look at the network, the first request is not cancelled when the second request is submitted.
Thanks in advance for the help.
Upvotes: 0
Views: 1346
Reputation: 8331
Have a look at this awesome directive by @Doug R which adds a delay to ng-change.
This totally saved my day because we have some very fast typers at my office. This will only fire after a certain amount of typing inactivity (300 - 500ms are a good value to start with)
Another way would be to react with ng-blur or force the user to press RETURN to update the list.
Upvotes: 1