Let’s implement text suggestions functionality using AngularJS. It provides suggestions while we type into the text field. For example, if we have a list of fruits and the user types ‘ap’, it will show all fruit names that contain these letters.
I have also included and used jquery library in this code. Inside FruitsController, we initialized a list of fruits, which is used to show fruit names on the page using ng-repeat in line 23. Initially, we hide this list using css, so that user can see suggestions only after they start typing into the text box.
The text box is bound to a variable ‘query’, which means whatever user types in the textbox, is contained in the query variable.
<p ng-repeat="fruit in fruits>
will display a list of all fruits. We are passing its output to filter function. The filter function uses the query value to create a new array that contains only those records that match the query.
Whenever user types something into the textbox, the change event is fired and we bind it to a function toggleGuess using ng-change directive of AngularJS. toggleGuess function uses jquery to check if user has typed something into the textbox and if it is so, it displays the list of fruits that matches the query. If textbox goes empty, it hides the list of fruits.
Read Further on AngularJS Series
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS