Open In App

Building a Search Functionality using AngularJS Services

Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. An Angular service is a broad category that consists of any value, function, or feature that an application needs. A service is a class with a narrow and well-defined purpose.

In this article, we’ll see how to build a search functionality using the AngularJS services. The search functionality is a critical component of any application that deals with large amounts of data. Angular provides a way to create a custom service that encapsulates the search logic and can be injected into different components of the application allowing the users to search for data based on a keyword. This approach helps in creating a more modular and maintainable codebase. 

Syntax:

var search = function(keyword) {
    return data.filter(function(item) {
        return item.name.toLowerCase()
            .indexOf(keyword.toLowerCase()) !== -1;
    });
};

Steps to create a search functionality: The below procedure will be implemented to create the search functionality:

Step 1: Create an AngularJS module: First, we create a module with the help of angular.module() function and give it a name like “myApp”:

angular.module('myApp', []);

Step 2: Create an AngularJS factory to encapsulate the search functionality

A factory function is a way to define a reusable object that can be injected into other parts of the application. In this example, we’ll use a factory to define a search function that takes a search keyword and returns an array of matching results. Here’s an example of a search factory:

angular.module('myApp')
.factory('searchFactory', function() {
    var data = [
        { id: 1, name: 'Stack' },
        { id: 2, name: 'Queue'},
        ...
    ];

    var search = function(keyword) {
        return data.filter(function(item) {
            return item.name.toLowerCase()
                .indexOf(keyword.toLowerCase()) !== -1;
        });
    };

    return {
        search: search
    };
});

Step 3: Create an AngularJS controller to handle the search functionality

A controller function is a way to define the behavior of a view in AngularJS. In this example, we’ll use a controller to get the search keyword from the view, call the search function from the factory, and display the search results in the view. Here’s an example of a search controller:

angular.module('myApp')
.controller('searchCtrl', function($scope, searchFactory) {
    $scope.searchKeyword = '';
    $scope.searchResults = [];

    $scope.search = function() {
        $scope.searchResults = searchFactory
            .search($scope.searchKeyword);
    };
});

Step 4: Add an ng-controller attribute to the body element, and set it to the name of the controller:

<body ng-controller="searchCtrl">

Step 5: Add an input element and a button element for the search functionality:

<input type="text" 
       ng-model="searchKeyword" 
       placeholder="Search...">
<button ng-click="search()">
    Search
</button>

Step 6: Add an element to display the search results using the ng-repeat directive to iterate over the searchResults array in the controller:

<div ng-repeat="result in searchResults">
    {{ result.name }}
</div>

The below example demonstrates how to build a search functionality using AngularJS.

Example 1: In this example, we have used the factory function where the data is also loaded using the service and the controller uses the service to search for data and displays the search results using the $scope object.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <meta charset="UTF-8">
    <title>Search Example</title>
    <script src=
    </script>
    <script>
        angular.module('myApp', [])
            .service('searchService', function () {
                var searchData = [];
  
                var data = [{
                    id: 1,
                    name: 'Array'
                },
                {
                    id: 2,
                    name: 'Linked List'
                },
                {
                    id: 3,
                    name: 'Stack'
                },
                {
                    id: 3,
                    name: 'Queue'
                }
                ];
  
                this.search = function (keyword) {
                    searchData = data.filter(function (item) {
                        return item.name.toLowerCase().
                        indexOf(keyword.toLowerCase()) !== -1;
                    });
                    return searchData;
                };
            })
            .controller('searchCtrl', function (searchService) {
                var vm = this;
                vm.searchKeyword = '';
                vm.searchResults = [];
                vm.search = function () {
                    vm.searchResults = 
                      searchService.search(vm.searchKeyword);
                };
            });
    </script>
</head>
  
<body ng-controller="searchCtrl as search">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>
        Building a search functionality
        using AngularJS services
    </h3>
    <h3>Search Data Structures</h3>
    <div>
        <input type="text" 
               ng-model="search.searchKeyword" 
               placeholder="Search...">
        <button ng-click="search.search()">
            Search
        </button>
    </div>
  
    <div ng-if="search.searchResults.length > 0">
        <ul>
            <li ng-repeat="result in search.searchResults">
                {{ result.name }}
            </li>
        </ul>
    </div>
  
    <div ng-if="search.searchResults.length === 0">
        <p>No results!</p>
    </div>
</body>
  
</html>


Output:

 

Example 2: In this example, we have used the factory function however the data has been hard-coded in the controller and the controller uses the service to search for data and displays the search results using the $scope object.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <meta charset="UTF-8">
    <title>Search Example</title>
    <script src=
    </script>
    <script>
        angular.module('myApp', [])
            .factory('searchData', function () {
                var data = [{
                    id: 1,
                    name: 'Array'
                },
                {
                    id: 2,
                    name: 'Linked List'
                },
                {
                    id: 3,
                    name: 'Stack'
                },
                {
                    id: 3,
                    name: 'Queue'
                }
                ];
  
                var search = function (keyword) {
                    return data.filter(function (item) {
                        return item.name.toLowerCase().
                        indexOf(keyword.toLowerCase()) !== -1;
                    });
                };
  
                return {
                    search: search
                };
            })
            .controller('searchCtrl', function ($scope, searchData) {
                $scope.searchKeyword = '';
                $scope.searchResults = [];
  
                $scope.search = function () {
                    $scope.searchResults = 
                        searchData.search($scope.searchKeyword);
                };
            });
    </script>
</head>
  
<body ng-controller="searchCtrl">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>
        Building a search functionality
        using AngularJS services
    </h3>
    <h3>Search Data Structures</h3>
    <div>
        <input type="text" 
               ng-model="searchKeyword" 
               placeholder="Search...">
        <button ng-click="search()">
            Search
        </button>
    </div>
  
    <div ng-if="searchResults.length > 0">
        <ul>
            <li ng-repeat="result in searchResults">
                {{ result.name }}
            </li>
        </ul>
    </div>
  
    <div ng-if="searchResults.length === 0">
        <p>No results!</p>
    </div>
</body>
  
</html>


Output:

 



Last Updated : 28 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads