A very common feature in several parts of my application is a search box that accepts a string and then filters an table based on the string.
What I am aiming for is the ability to permit user to type in something and automatically after a few ms of delay the results update themselves. i.e no need to hit the enter button.
Ofcourse sorting of the data would be done using AngularJs filters. However before we update the filter I believe we first have to understand that the user has completed entering the input and is now waiting for the results.
So I mapped out the directive which will be attached to the search input box .
<input type="text" update-filter placeholder="Enter search term">
//and the directive goes like this
app.directive('updateFilter', [ '$timeout', function($timeout){
var delay;
return {
link: function(scope, element){
element.on('keypress', function(){
if(!delay) {
delay = $timeout(function() {
//perform the activity of updating the filter here
delay = undefined;
},50);
}
}
}
}
});
My question is, is this the right approach to take to tackle this issue or are there better solutions out there ?
You are overcomplicating this. It can be done much easier in angular.
<input type="text" ng-model="query" ng-model-options="{ debounce: 200 }"
ng-change="doSearch()">
Use $scope.query
to access the query in your controller. Define $scope.doSearch()
to do the search. The debounce option is used to wait 200ms after the user is done typing.
When I write a filter, I use ng-model on the filter input to get access to the filter value, and then use that value directly in the ng-repeat filter value. For instance, here's the input to get the filter value:
<input type="text" ng-model="user_filter" />
And here's a repeating table row, filtered by the value modeled above:
<tr ng-repeat="user in users | filter: user_filter">
As soon as you type, angular registers the new value and the filter is applied. There is no need to wait or perform any action because angular applies the mapped values for you.
Check out the Angular docs on filter. It has a working example at the bottom of the page that shows this in action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With