Identifying Whether Angular ng-repeat is Displaying Output or Not

I am trying to display a "No result" message when the search field does not have any matches. The current filter is working fine, but it does not show the message when there are no results. How can I achieve this?

<div class="portfolio-list-wrap" ng-controller="LatestProjectCtrl">
<input type="text" ng-model="search.$"/>
<div class="portfolio-thumb" ng-repeat="work in works.project | filter:search">
    <img src="images/{{work.string}}.jpg" alt="{{work.name}}"/>
    <h4>{{work.name}}</h4>
    <i>{{work.date}}</i>
</div>
</div>

Here is my factory implementation:

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


myApp.factory('Works', function(){

var Works = {}

Works.project =[
    {
        name : "project1",
        string : "projectstring1",
        date: "17 August 2012"
    },
    {
        name : "project2",
        string : "projectstring2",
        date: "12 December 2013"
    },
    {
        name : "project3",
        string : "projectstring3",
        date: "17 September 2012"
    },
    {
        name : "project3",
        string : "projectstring4",
        date: "17 August 2012"
    },
];  
return Works;
})



function LatestProjectCtrl($scope, Works){
$scope.works = Works;
}

Answer №1

If there are no results, you can display a message like this:

<span ng-show="(projects | filter:query).length == 0">No results</span>

Check out the full example below:

function Controller($scope) {
  $scope.projects = [
      {
        name: "Sunny project 1",
        date: "17.3.2016",
        image: "pr1"
      },
      {
        name: "Windy project 2",
        date: "18.03.2016",
        image: "pr2"
      },
      {
        name: "Cloudy project 3",
        date: "19.03.2016",
        image: "pr3"
      }
    ]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <div ng-controller="Controller">
    <input type="text" ng-model="query" />
    <div class="portfolio-thumb" ng-repeat="project in projects | filter:query">
      <h4>{{project.name}}</h4>
      <ul>
        <li>{{project.date}}</li>
        <li>Img source = '{{project.image}}.jpg'</li>
      </ul>
    </div>
    <div ng-show="(projects | filter:query).length == 0">No results</div>
  </div>
</div>

Answer №2

Give this a shot.

<div class="portfolio-thumb" ng-repeat="work in filteredList = (works.project | filter:search)">
    <img src="images/{{work.string}}.jpg" alt="{{work.name}}"/>
    <h4>{{work.name}}</h4>
    <i>{{work.date}}</i>

</div>
<span ng-hide="filteredList.length"> No results found</span>

JSFiddle link

Update:

A more elegant solution is to use

 <span ng-hide="filteredList"> No results found</span>

Updated JSFiddle link

Answer №3

Ensure your website has the option to show and hide error messages

<div class="portfolio-list-wrap" ng-controller="LatestProjectCtrl">
<input type="text" ng-model="search.$"/>
<h2 ng-if="works.project===undefined || works.project.length===0">You have no results</h2>
<div ng-if="works.project!==undefined || works.project.length!==0" >
<div class="portfolio-thumb" ng-repeat="work in works.project | filter:search">
    <img src="images/{{work.string}}.jpg" alt="{{work.name}}"/>
    <h4>{{work.name}}</h4>
    <i>{{work.date}}</i>
</div>
</div>
 </div>

If works.project is undefined, display an error message. Otherwise, show the div.

Review these conditions:

<h2 ng-if="works.project===undefined || works.project.length===0">You have no results</h2>
    <div ng-if="works.project!==undefined || works.project.length!==0" >...

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

The functionality of res.send is not working correctly

Attempting to send a response from my express application to the front-end in order to display an alert. Here is what I have attempted in my app: if (info.messageId) { res.redirect('back'); res.send({ success: true }); } ...

Having trouble establishing a connection between Node.js and SQL Server using Tedious library

When attempting to connect to a local SQL Server instance using Node.js and Tedioius, I encounter the following error: { [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed ...

What is the best way to extract text from a dynamically changing element using jQuery?

I've been struggling with a coding issue. Despite trying numerous approaches, I keep encountering the same problem where every new button I add ends up having the same text or, alternatively, nothing seems to work as expected. $j serves as my variabl ...

"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. ...

Crafty Checkbox Selector [ leveraging jquery ]

I have created some fake checkboxes using elements like <span> after the real checkbox and they are working fine! However, I am having trouble counting the checked checkboxes when a checkbox is clicked. I have tried using methods like: $(".elm:chec ...

Understanding the proper way to enclose JSX components and exhibit JSON based on user input

I'm currently working on a university administration website using React that needs to support multiple languages. I have successfully built the Login page, which you can see here: https://i.stack.imgur.com/cIiaU.png Now, my next task is to allow us ...

Navigating tables with jQuery using a loop and extracting data from two tables with matching row names

I am facing a challenge with a function that combines data from two tables, each containing a column named "name". How can I specify which table's name should be displayed? function createTableRow(customers) { var data = JSON.parse(customers.resu ...

Is there a way to stop the execution of myFunc after it has been performed 5 times using clearInterval?

This code is designed to notify online shoppers that they need to choose a color from a dropdown menu before adding an item to their shopping cart. If no color is selected, the text will blink to alert them. How can I modify this code so that the blinking ...

Passing a single item from a list as a prop in Vue.js

Imagine having the following set of information in data: data: { todos: [ { id: 1, title: "Learn Python" }, { id: 2, title: "Learn JS" }, { id: 3, title: "Create WebApp" } ] } Now, I aim to send only the item with an id of 2 t ...

Choosing all components except for one and its descendants

I am searching for a method to choose all elements except for one specific element and its descendant, which may contain various levels of children/grandchildren or more. What I'm trying to accomplish is something like... $("*").not(".foo, .foo *").b ...

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

The hyperlink and criteria provided are accurate, however, the webpage remains stagnant

My login page is supposed to redirect to the contact confirmation page when I receive a 200 response from the server, but it's not working. Can you help me find my mistake? const [form, setForm] = useState({}); async function checkLogin() { tr ...

Comparing AngularJS $http with $http.post: A Detailed Analysis

As a newcomer to AngularJS, I am experimenting with sending data to the server and mapping it to a DTO in a REST Service. Here's how I attempted to do it: saveUserUrl = "http://localhost:8080/App/rest/UserManager/saveUser"; var res ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Comparing jQuery and Yahoo UI API Design

I find myself puzzled by the contrasting design approaches of jQuery and Yahoo UI APIs. I must confess, I have a strong aversion to the jQuery API, but my knowledge in web programming and JavaScript is limited, so I could be completely mistaken and end up ...

When the canvasJS range column chart is below the horizontal axis, modify the color and width of the bars

For each day of the week, there are records of fuel consumed and refilled. I envisioned representing this data in a range column chart using CanvasJS library. The unique aspect is that the color and width of the bars should change dynamically based on thei ...

Exporting State From Another ReactJS Module: A Step-by-Step Guide

A new project is underway with 3 students who are diving into the world of React for the first time. To make our work more efficient, I suggested dividing the code so that each student could work on a different aspect simultaneously. However, when I attemp ...

Submitting a form using jquery

I am working on a project that involves using a jquery fancyzoom box. Within this box, there is a contact form that should send an email upon submission. However, I am encountering issues with calling the form submit function due to the fancyzoom feature. ...

Simultaneous malfunction of two ajax forms

I have a dilemma with two boxes: one is called "min amount" and the other is called "max amount." Currently, if I input 100 in the max amount box, it will display products that are priced at less than $100. However, when I input an amount like $50 in the m ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...