1. First, create a new AngularJS module for your autocomplete feature. This can be done using the angular.module function, like so:
var app = angular.module('myApp', []);
2. Next, create a new directive that will be responsible for handling the autocomplete functionality. In this example, we’ll call it “autocomplete”:
app.directive('autocomplete', function() { return { restrict: 'A', scope: { options: '=', ngModel: '=' }, template: '<input type="text" ng-model="ngModel">' + '<div ng-show="isVisible">' + '<div ng-repeat="option in filteredOptions" ng-click="selectOption(option)">{{option}}</div>' + '</div>', link: function(scope, element, attrs) { // Autocomplete logic goes here } } });
The directive has an template with an input box and a list with options, and a link function, where all the logic for autocomplete goes.
3. Inside the link function, you’ll need to add logic to filter the options based on the user’s input and display a list of matching options. Here’s an example of how you might do this:
link: function(scope, element, attrs) { scope.isVisible = false; element.find('input').on('keyup', function() { scope.filteredOptions = scope.options.filter(function(option) { return option.indexOf(scope.ngModel) === 0; }); scope.isVisible = scope.filteredOptions.length > 0; scope.$apply(); }); }
4. Add ng-model and options attribute with options list in the element you are using this autocomplete directive,
<div autocomplete options="options" ng-model="selectedOption"></div>
5. And Finally in your controller, you need to define the options list
app.controller('myCtrl', function($scope) { $scope.options = ['Option 1', 'Option 2', 'Option 3', 'Option 4']; });
This is a basic example of how you might implement an autocomplete feature in AngularJS. Depending on your specific requirements, you may need to add additional logic or features, such as handling keyboard events to navigate through the list of options or handling cases where the user has entered an invalid input.