The right way to program your search text box in angularJs

Very often in some parts of my application there is a search box that takes a row and then filters the table based on the row.

What I am aiming at is the ability to allow the user to enter something and automatically after a few ms of delay, when the results are updated themselves. no need to press the enter button.

Data will be sorted using AngularJs filters. However, before we update the filter, I believe that we first need to understand that the user has completed input and is now waiting for the results.

So, I have outlined a directive that will be attached to the search input field.

<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 approach right for solving this problem or are there better solutions there?

+5
source share
2 answers

You are excessive. This can be made much simpler 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 200 ms after a user enters a command.

+9
source

When I write a filter, I use ng-model in the filter input to access the filter value and then use that value directly in the ng-repeat filter value. For example, here is the input to get the filter value:

 <input type="text" ng-model="user_filter" /> 

And here is a repeating table row filtered by the value modeled above:

 <tr ng-repeat="user in users | filter: user_filter"> 

Once you type, angular registers the new value and a filter is applied. There is no need to wait or take any action because angular applies the mapped values ​​for you.

View the Angular docs in the filter . At the bottom of the page there is a working example that shows this in action.

+5
source

Source: https://habr.com/ru/post/1206874/


All Articles