Ibrahim Gidi
Ibrahim Gidi

Reputation: 59

AngularJS: Unable to Display Found Items in Search Functionality

I'm working on an AngularJS project where I have implemented a search functionality to filter menu items based on a user-entered search term. However, I'm encountering an issue where the found items are not being displayed in the UI even though the search functionality seems to be working correctly.

Problem Description:

When a user enters a search term and clicks the "Narrow It Down For Me!" button, the application should fetch the menu items from a REST API, filter them based on the search term, and display the found items in the UI. However, while the HTTP request is successful and the filtering logic appears to work fine (verified through console logs), the found items are not being rendered in the UI.

Steps to Reproduce:

Enter a search term into the text input box.
Click the "Narrow It Down For Me!" button.
Observe that no items are displayed in the UI, even though there are matching items.

Expected Behavior:

After entering a search term and clicking the button, the UI should display a list of found items that match the search criteria.

Actual Behavior:

The UI does not display any found items, even though the search functionality appears to be working correctly.

Code Snippets:

1. app.js

// app.js
(function () {
    'use strict';

    angular.module('NarrowItDownApp', [])
        .controller('NarrowItDownController', NarrowItDownController)
        .service('MenuSearchService', MenuSearchService)
        .directive('foundItems', foundItemsDirective);

    NarrowItDownController.$inject = ['MenuSearchService'];
    function NarrowItDownController(MenuSearchService) {
        var ctrl = this;
        ctrl.searchTerm = '';
        ctrl.found = [];

        ctrl.narrowItDown = function () {
            console.log('searchterm:',ctrl.searchTerm);
            if (ctrl.searchTerm.trim() !== '') {
                MenuSearchService.getMatchedMenuItems(ctrl.searchTerm)
                    .then(function (foundItems) {
                        ctrl.found = foundItems;
                    })
                    .catch(function (error) {
                        console.error('Error narrowing down menu items:', error);
                    });
            } else {
                ctrl.found = [];
            }
        };

        ctrl.removeItem = function (index) {
            ctrl.found.splice(index, 1);
        };

        ctrl.isEmpty = function () {
            return ctrl.found.length === 0 && ctrl.searchTerm.trim() !== '';
        };
    }

    MenuSearchService.$inject = ['$http', '$q'];
    function MenuSearchService($http, $q) {
        var service = this;

        service.getMatchedMenuItems = function (searchTerm) {
            return $http({
                method: 'GET',
                url: 'https://coursera-jhu-default-rtdb.firebaseio.com/menu_items.json'
            }).then(function (result) {
                var foundItems = [];
                var menuItems = result.data;
                console.log(menuItems);

                // Iterate over the properties of the object
                for (var key in menuItems) {
                    if (menuItems.hasOwnProperty(key)) {
                        var categoryItems = menuItems[key];

                        // Iterate over the items in the category
                        for (var itemKey in categoryItems) {
                            if (categoryItems.hasOwnProperty(itemKey)) {
                                var item = categoryItems[itemKey];

                                // Check if the item has a description property and if it matches the search term
                                if (item.description && item.description.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1) {
                                    foundItems.push(item);
                                }
                            }
                        }
                    }
                }
                console.log(foundItems)
                return foundItems;
            }).catch(function (error) {
                // Handle HTTP request errors
                console.error('Error fetching menu items:', error);
                return $q.reject(error);
            });
        };
    }

    function foundItemsDirective() {
        var ddo = {
            templateUrl: 'foundItems.html',
            scope: {
                items: '<',
                onRemove: '&'
            }
        };

        return ddo;
    }

})();

2. index.html

<!DOCTYPE html>
<html ng-app="NarrowItDownApp">
<head>
    <title>Menu Search App</title>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <!-- Include app.js -->
    <script src="app.js"></script>
</head>
<body>
    <div ng-controller="NarrowItDownController as ctrl">
        <input type="text" ng-model="ctrl.searchTerm" placeholder="Enter search term">
        <button ng-click="ctrl.narrowItDown()">Narrow It Down For Me!</button>
        
        <div ng-if="ctrl.isEmpty()">Nothing found</div>

        <!-- Inline template for foundItems directive -->
        <div>
            <ul>
                <li ng-repeat="item in ctrl.found">
                    <h4>{{ item.name }}</h4>
                    <p>{{ item.short_name }}, {{ item.description }}</p>
                    <button ng-click="ctrl.removeItem($index)">Don't want this one!</button>
                </li>
            </ul>
        </div>
    </div>
</body>
</html>

Screen shot of the page: enter image description here

Upvotes: 0

Views: 13

Answers (0)

Related Questions