Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to program a search text box in angularJs

Tags:

angularjs

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 ?

like image 875
runtimeZero Avatar asked Nov 14 '14 14:11

runtimeZero


2 Answers

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.

like image 178
wvdz Avatar answered Nov 16 '22 19:11

wvdz


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.

like image 6
Surreal Dreams Avatar answered Nov 16 '22 19:11

Surreal Dreams