Table of Contents
Key Takeaways
Overview
Configuration Options
Step 1: Building a Factory for Getting Data
Step 2: Creating the Directive
Step 3: Create the Template
Step 4: Update the link Function
Step 5: Configure and Use the Directive
Conclusion
Frequently Asked Questions on Creating a Typeahead Widget with AngularJS
How can I customize the appearance of the typeahead dropdown?
How can I limit the number of suggestions in the typeahead dropdown?
How can I use an object selection functionality with typeahead?
How can I use typeahead with Bootstrap in AngularJS?
How can I use typeahead with remote data in AngularJS?
Home Web Front-end JS Tutorial Creating a Typeahead Widget with AngularJS - SitePoint

Creating a Typeahead Widget with AngularJS - SitePoint

Feb 22, 2025 am 08:44 AM

Creating a Typeahead Widget with AngularJS - SitePoint

Creating a Typeahead Widget with AngularJS - SitePoint

If you are starting an AngularJS project you might want to have all the components written in Angular. Although it’s certainly possible to reuse the existing jQuery plugins, throwing a bunch of jQuery inside a directive is not always the correct way to do things. My advice would be to first check if the same thing can be implemented with pure Angular in a simpler/better way. This keeps your application code clean and maintainable. This tutorial, targeted towards beginners, walks the readers through the creation of a simple TypeAhead widget with AngularJS.

Key Takeaways

  • The tutorial guides readers through creating a TypeAhead widget with AngularJS, which provides suggestions as a user types into a text box. The widget is designed to be highly configurable and easily integrated into existing systems.
  • The process involves building a factory that interacts with a RESTful API and returns JSON data for auto-complete suggestions, creating a directive to encapsulate the typeahead input field, and creating a template for the directive. The directive is kept configurable for end users to adjust options such as the JSON object properties to show as part of the suggestions and the model in the controller’s scope that will hold the selected item.
  • The tutorial also explains how to update the link function of the directive and configure the directive for use. The final product is an AngularJS TypeAhead widget with configuration options, which can be customized further using CSS. The complete source code is available for download on GitHub.

Overview

In this tutorial we are going to build a simple TypeAhead widget which creates suggestions as soon as someone begins typing into a text box. We will architect the app in such a way that the final product will be very configurable and can be plugged into an existing system easily. The basic steps involved in the creation process are:
  • Create a factory that interacts with a RESTful API, and returns JSON that will be used for auto complete suggestions.
  • Create a directive that will use the JSON data and encapsulate the typeahead input field.
  • Keep the directive configurable so that end users can configure the following options.

Configuration Options

  1. The exact JSON object properties to show as part of the suggestions.
  2. The model in the controller’s scope that will hold the selected item.
  3. A function in the controller’s scope that executes when an item is selected.
  4. A placeholder text (prompt) for the typeahead input field.

Step 1: Building a Factory for Getting Data

As the first step, let’s create a factory that uses Angular’s $http service to interact with RESTful APIs. Have a look at the following snippet:
<span>var typeAhead = angular.module('app', []);
</span>
typeAhead<span>.factory('dataFactory', function($http) {
</span>  <span>return {
</span>    <span>get: function(url) {
</span>      <span>return $http.get(url).then(function(resp) {
</span>        <span>return resp.data; // success callback returns this
</span>      <span>});
</span>    <span>}
</span>  <span>};
</span><span>});</span>
Copy after login
Copy after login
The previous code creates a factory called dataFactory that retrieves JSON data from an API. We won’t go into the details of the factory, but we need to briefly understand how the $http service works. You pass a URL to the get() function, which returns a promise. Another call to then() on this promise also returns another promise (we return this promise from the factory’s get() function). This promise is resolved with the return value of the success callback passed to then(). So, inside our controller, we don’t directly interact with $http. Instead, we ask for an instance of factory in the controller and call its get() function with a URL. So, our controller code that interacts with the factory looks like this:
typeAhead<span>.controller('TypeAheadController', function($scope<span>, dataFactory</span>) { // DI in action
</span>  dataFactory<span>.get('states.json').then(function(data) {
</span>    $scope<span>.items = data;
</span>  <span>});
</span>  $scope<span>.name = ''; // This will hold the selected item
</span>  $scope<span>.onItemSelected = function() { // this gets executed when an item is selected
</span>    <span>console.log('selected=' + $scope.name);
</span>  <span>};
</span><span>});</span>
Copy after login
Copy after login
The previous code uses an API endpoint called states.json that returns a JSON list of US States. When the data is available, we store the list in the scope model items. We also use the model name to hold the selected item. Finally, the function onItemSelected() gets executed when the user selects a particular state.

Step 2: Creating the Directive

Let’s start with the typeahead directive, shown below.
typeAhead<span>.directive('typeahead', function($timeout) {
</span>  <span>return {
</span>    <span>restrict: 'AEC',
</span>    <span>scope: {
</span>      <span>items: '=',
</span>      <span>prompt: '@',
</span>      <span>title: '@',
</span>      <span>subtitle: '@',
</span>      <span>model: '=',
</span>      <span>onSelect: '&amp;'
</span>    <span>},
</span>    <span>link: function(scope<span>, elem, attrs</span>) {
</span>    <span>},
</span>    <span>templateUrl: 'templates/templateurl.html'
</span>  <span>};
</span><span>});</span>
Copy after login
Copy after login
In the directive we are creating an isolated scope that defines several properties:
  • items: Used to pass the JSON list to the isolated scope.
  • prompt: One way binding for passing placeholder text for the typeahead input field.
  • title and subtitle: Each entry of the auto complete field has a title and subtitle. Most of the typeAhead widgets work this way. They usually (if not always) have two fields for each entry in the drop down suggestions. If a JSON object has additional properties, this acts as a way of passing the two properties that will be displayed in each suggestion in the dropdown. In our case the title corresponds to the name of the state, while subtitle represents its abbreviation.
  • model: Two way binding to store the selection.
  • onSelect: Method binding, used to execute the function in the controller scope once the selection is over.
Note: An example JSON response is shown below:
<span>var typeAhead = angular.module('app', []);
</span>
typeAhead<span>.factory('dataFactory', function($http) {
</span>  <span>return {
</span>    <span>get: function(url) {
</span>      <span>return $http.get(url).then(function(resp) {
</span>        <span>return resp.data; // success callback returns this
</span>      <span>});
</span>    <span>}
</span>  <span>};
</span><span>});</span>
Copy after login
Copy after login

Step 3: Create the Template

Now, let’s create a template that will be used by the directive.
typeAhead<span>.controller('TypeAheadController', function($scope<span>, dataFactory</span>) { // DI in action
</span>  dataFactory<span>.get('states.json').then(function(data) {
</span>    $scope<span>.items = data;
</span>  <span>});
</span>  $scope<span>.name = ''; // This will hold the selected item
</span>  $scope<span>.onItemSelected = function() { // this gets executed when an item is selected
</span>    <span>console.log('selected=' + $scope.name);
</span>  <span>};
</span><span>});</span>
Copy after login
Copy after login
First, we render an input text field where the user will type. The scope property prompt is assigned to the placeholder attribute. Next, we loop through the list of states and display the name and abbreviation properties. These property names are configured via the title and subtitle scope properties. The directives ng-mouseenter and ng-class are used to highlight the entry when a user hovers with the mouse. Next, we use filter:model, which filters the list by the text entered into the input field. Finally, we used the ng-hide directive to hide the list when either the input text field is empty or the user has selected an item. The selected property is set to true inside the handleSelection() function, and set to false false (to show the suggestions list) when someone starts typing into the input field. Next, let’s update the link function of our directive as shown below.
typeAhead<span>.directive('typeahead', function($timeout) {
</span>  <span>return {
</span>    <span>restrict: 'AEC',
</span>    <span>scope: {
</span>      <span>items: '=',
</span>      <span>prompt: '@',
</span>      <span>title: '@',
</span>      <span>subtitle: '@',
</span>      <span>model: '=',
</span>      <span>onSelect: '&amp;'
</span>    <span>},
</span>    <span>link: function(scope<span>, elem, attrs</span>) {
</span>    <span>},
</span>    <span>templateUrl: 'templates/templateurl.html'
</span>  <span>};
</span><span>});</span>
Copy after login
Copy after login
The function handleSelection() updates the scope property, model, with the selected state name. Then, we reset the current and selected properties. Next, we call the function onSelect(). A delay is added because the assignment scope.model=selecteditem does not update the bound controller scope property immediately. It is desirable to execute the controller scope callback function after the model has been updated with the selected item. That’s the reason we have used a $timeout service. Furthermore, the functions isCurrent() and setCurrent() are used together in the template to highlight entries in the auto complete suggestion. The following CSS is also used to complete the highlight process.
<span>{
</span>  <span>"name": "Alabama",
</span>  <span>"abbreviation": "AL"
</span><span>}</span>
Copy after login

Step 5: Configure and Use the Directive

Finally, let’s invoke the directive in the HTML, as shown below.
<span><span><span><input</span> type<span>="text"</span> ng-model<span>="model"</span> placeholder<span>="{{prompt}}"</span> ng-keydown<span>="selected=false"</span> /></span>
</span><span><span><span><br</span>/></span>
</span>
<span><span><span><div</span> class<span>="items"</span> ng-hide<span>="!model.length || selected"</span>></span>
</span>  <span><span><span><div</span> class<span>="item"</span> ng-repeat<span>="item in items | filter:model  track by $index"</span> ng-click<span>="handleSelection(item[title])"</span> <span>style<span>="<span>cursor:pointer</span>"</span></span> ng-class<span>="{active:isCurrent($index)}"</span> ng-mouseenter<span>="setCurrent($index)"</span>></span>
</span>    <span><span><span><p</span> class<span>="title"</span>></span>{{item[title]}}<span><span></p</span>></span>
</span>    <span><span><span><p</span> class<span>="subtitle"</span>></span>{{item[subtitle]}}<span><span></p</span>></span>
</span>  <span><span><span></div</span>></span>
</span><span><span><span></div</span>></span></span>
Copy after login

Conclusion

This tutorial has shown you how to create an AngularJS TypeAhead widget with configuration options. The complete source code is available for download on GitHub. Feel free to comment if something is unclear or you want to improve anything. Also, don’t forget to check out the live demo.

Frequently Asked Questions on Creating a Typeahead Widget with AngularJS

How can I customize the appearance of the typeahead dropdown?

Customizing the appearance of the typeahead dropdown can be achieved by using CSS. You can target the dropdown menu by using the class .dropdown-menu. For instance, if you want to change the background color and font color, you can use the following CSS code:

.dropdown-menu {
background-color: #f8f9fa;
color: #343a40;
}
Remember to include this CSS in your main CSS file or within the

How can I limit the number of suggestions in the typeahead dropdown?

Limiting the number of suggestions in the typeahead dropdown can be done by using the typeahead-min-length attribute. This attribute specifies the minimum number of characters that must be entered before typeahead starts to kick in. For example, if you want to start showing suggestions after the user has typed 3 characters, you can use the following code:

How can I use an object selection functionality with typeahead?

To use an object selection functionality with typeahead, you can use the typeahead-on-select attribute. This attribute allows you to specify a function to be called when a match is selected. The function will be passed the selected item. For example:


In your controller, you can define the onSelect function like this:

$scope.onSelect = function (item, model, label) {
// Do something with the selected item
};

How can I use typeahead with Bootstrap in AngularJS?

To use typeahead with Bootstrap in AngularJS, you need to include the ui.bootstrap module in your AngularJS application. This module provides a set of AngularJS directives based on Bootstrap’s markup and CSS. The typeahead directive can be used as follows:


In this example, states is an array of states, $viewValue is the value entered by the user, and limitTo:8 limits the number of suggestions to 8.

How can I use typeahead with remote data in AngularJS?

To use typeahead with remote data in AngularJS, you can use the $http service to fetch data from a remote server. The typeahead attribute can be used to bind the input field to the fetched data. For example:

$scope.getStates = function(val) {
return $http.get('/api/states', {
params: {
name: val
}
}).then(function(response){
return response.data.map(function(item){
return item.name;
});
});
};
In your HTML, you can use the getStates function like this:


In this example, getStates is a function that fetches states from a remote server based on the value entered by the user.

The above is the detailed content of Creating a Typeahead Widget with AngularJS - SitePoint. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles