Angular JS not displaying texts properly

Within my code, I have implemented a feature to display an h4 element stating that there are no products found if the search query does not match any strings. However, I am encountering a strange bug where the text fails to appear as intended. Interestingly, the text becomes visible after interacting with elements that have click event bindings or making edits to the color in the CSS console. Despite trying numerous solutions, the issue persists. Any insights on what might be causing this behavior and how I can resolve it would be greatly appreciated.

The implementation looks like this:

<h4 ng-show="filteredItems.length == 0"  class="explanation">We found no products</h4>

CSS styling:

h4 {
    color: #ccc;
    text-align: center;
    padding: 100px 20px;
}

Search functionality:

$scope.searchItem = function(query) {
    var foundItems = [];
    query.toLowerCase();
    if (searchTimeout)
      $timeout.cancel(searchTimeout);

    searchTimeout = $timeout(function() {
      for (var i = 0; i < $scope.items.length; i++) {
        if ($scope.items[i].name.toLowerCase().indexOf(query) > -1) 
          foundItems.push($scope.items[i]);
      }

      $scope.filteredItems = foundItems;   

    }, 400);
}

EDIT

// fill with dummy data
$scope.define = function() {
    var random;
    for (var i = 0; i < 114; i++) {
      random = Math.floor(Math.random() * 6) + 1;
      var text;
      switch(random) {
        case 1:
            text = 'Double espresso';
            break;
        case 2:
            text = 'Frappuccino cookie crumble chocolate';
            break;
        case 3:
            text = 'Cappuccino';
            break;
        case 4:
            text = 'Very Berry Hibiscus Starbucks Refreshers™ Beverage';
            break;
        case 5:
            text = 'Clover® Brewed Coffee Coffee Traveler';
            break;
        case 6:
            text = 'Featured Dark Roast';
            break;
        default:
            text = 'Not defined';
      }
      $scope.data.items.push({ name: text, image: random });
    }
    // Uncomment everything works
    //$scope.data.filteredItems = $scope.data.items;
}
$scope.define();

Answer №1

Check out this example on Plunker. I have it up and running, doing what I believe you're looking for. In my code, I always prefix scope values like $scope.data.query instead of using just $scope.query. This approach helps prevent any conflicts with scope values in the view versus the controller.

Additionally, since you're already using ng-model, there's no need to pass the value from the view to the controller when the controller already has it. That's why I updated ng-change to only call searchItems().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing this as a function parameter in Jquery

HTML <input type="button" id="1" class="add" value="+" title="Add" onclick="set(this);"/> JS function set(obj){ alert(obj.id); } The code snippet provided above seems to have an issue. My Requirement I am looking for a solution that allows ...

Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component. For example, suppose I have a component structured like this: <template> <div class="cl"></div> </template> < ...

Tips for implementing a sticky sidebar in HTML5 with jQuery

I currently have two files: index.php and aside.php. I've already created the contents of aside.php. Now, I want to make the aside page sticky. To achieve this, I referred to the following link: http://codepen.io/pouretrebelle/pen/yvcBz My struggle ...

PHP SQL bug causing incorrect username displays

This logon script is functioning well on my website: <?php include 'pdo_connect.php'; if(!empty($_POST)) { $query = "SELECT `password` FROM `users` WHERE `uname` = ?"; $params = array($_POST['uname']); $results = data ...

Incorporate a Javascript session into MVC 4 Razor for enhanced functionality

I am currently developing an application that allows users to upload files. Before uploading the file, I need to configure the file storage settings. The first step is to read the first ten rows of the file and display them to the user. The user can then p ...

Encountering an unexpected issue with $urlMatcherFactory during an AngularJS service unit test

I am seeking guidance on writing a proper unit test for a service using the jasmine framework and karma as the test runner. Below is the implementation in example-service.js: export default class ExampleService { constructor($resource, $http, $urlMatcher ...

Innovative and interactive animated data display

I've taken inspiration from an example and expanded the code to achieve the following: Dynamic height adjustment Accessibility without JavaScript enabled Is this implementation correct? Can it be expected to function properly on most browsers? You ...

Elements appearing distorted in Firefox and Internet Explorer

I'm completely new to the world of web development and I am attempting to construct a website for my company all by myself. However, I am encountering an issue with a "red info box" on one of my pages. While it displays perfectly on Chrome, it appear ...

Simple Solutions for Moving Containers Up in Angular When Clicked

In the left side container, I have a header and sub-header, while the right side container contains text. However, whenever I click on the sub-header to display text on the right side, both container positions shift upward, hiding the header text. I'm ...

Steps to execute a JSON file once another JSON has been successfully loaded

I'm facing a similar challenge to the one presented in this question. However, I need to load an additional JSON file after the when() method is executed. Essentially, I want to retrieve JSON data within the when() function and then use that informati ...

I want to use the enter key for posting, but also have the ability to use the shift and enter key to create a

$("#post_text").keydown(function(e){ // Checking if Enter key was pressed without shift key if (e.keyCode == 13) { // Prevent default behavior e.preventDefault(); } if (e.keyCode == 13 && !e.shiftKey) { alert('test'); } }); I a ...

There seems to be a glitch with jQuery on my Angular.js website

I'm trying to implement Masonry.js on my website, and although I've managed to make it work, the solution feels like a messy workaround and I can't quite figure out why it's functioning (and not functioning well). The primary issues I& ...

Issue with JS npm package: Unable to use import statement outside a module

I recently attempted to utilize the npm package found at https://github.com/nefe/number-precision. However, despite following the prescribed steps, I encountered some difficulties. After running npm install number-precision --save--dep, I tried impor ...

Having trouble with the animate() function not working properly?

I have been working on the following code snippet: var isOn = false; $('.switch').on("click",function(){ if (isOn){ $('.toggle').animate({ left:"18px" },10,"linear", { complete: function(){ $(&ap ...

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

Creating movement effects for a line on an HTML5 canvas following a previous animation

I am facing an issue where my straight line starts animating towards the circle right at the beginning of page load. I am struggling with finding the logic to make the line animate in the opposite direction after the first animation is completed (which is ...

What steps can be taken to troubleshoot issues with the jquery mask plugin?

I am using the jQuery Mask Plugin available at to apply masks to input fields on my website. Currently, I am trying to implement a mask that starts with +38 (0XX) XXX-XX-XX. However, I am facing an issue where instead of mandating a zero in some places, ...

Switch the parent container in AngularJS by utilizing ng-click functionality

Within two distinct containers, one container holds a button. Upon clicking it, this button should move to the second container. I am familiar with achieving this using jQuery: $(document).on('click', '.drag', function(){ if($(thi ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...