Issue
I have this directive for a search box
// Define the search-box
alSH.directive('searchBox',[function(){
return {
restrict: 'E',
template: `
<input
placeholder="Search.."
class="search-box"
ng-keyup=search($evt)
ng-model="query"
ng-model-options="{ debounce: 1000 }"
/>`,
controller: function SearchBoxController($scope, helper) {
$scope.query = ''; //ng model
$scope.search = function() { //this calls in every keyup event
helper.setQuery($scope.query).search();
};
helper.setQuery('').search();
}
};
}]);
and i tried to use ng-model-options="{ debounce: 1000 }"
but still it keeps sending a network request for each key stroke without updating the ng-model
probably due to the ng-keyup
.
I found this post which asks for something similar but I didn't seem to understand the solution
I have added a codepen demo which has the above code snippet where I'm trying to achieve this behavior
Ideally I would like to limit the number of backend calls sent due to each key stroke. Any idea how to achieve this?
Solution
After doing some testing with an answer provided here I managed to add the debouncing.
I removed the ng-keyup=search($evt)
but kept the ng-model-options="{ debounce: 1000 }"
.
<input
placeholder="Search.."
class="search-box"
ng-model="query"
ng-model-options="{ debounce: 1000 }"
/>
Then in the controller added a watcher which keeps track of the $scope.query
variable which triggers the search function. To keep it simple i didn't use the values of newValue
and oldValue
but extra functionality can be achieved using those as well if needed. solved codepen
$scope.$watch('query', function (newValue, oldValue) {
$scope.search();
});
Answered By - cmgchess
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.