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
- The exact JSON object properties to show as part of the suggestions.
- The model in the controller’s scope that will hold the selected item.
- A function in the controller’s scope that executes when an item is selected.
- 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>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>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: '&' </span> <span>}, </span> <span>link: function(scope<span>, elem, attrs</span>) { </span> <span>}, </span> <span>templateUrl: 'templates/templateurl.html' </span> <span>}; </span><span>});</span>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.
<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>
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>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.
Step 4: Update the link Function
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: '&' </span> <span>}, </span> <span>link: function(scope<span>, elem, attrs</span>) { </span> <span>}, </span> <span>templateUrl: 'templates/templateurl.html' </span> <span>}; </span><span>});</span>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>
Step 5: Configure and Use the Directive
Finally, let’s invoke the directive in the HTML, as shown below.<span><span><span><input> 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><div> class<span>="items"</span> ng-hide<span>="!model.length || selected"</span>> <span><span><span><div> 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><p> class<span>="title"</span>></p></span>{{item[title]}}<span><span></span>></span> </span> <span><span><span><p> class<span>="subtitle"</span>></p></span>{{item[subtitle]}}<span><span></span>></span> </span> <span><span><span></span></span></span></span></span> </div></span>></span> </span><span><span><span></span></span></span> </div></span>></span></span></span></span>
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!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
