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

Tips for preventing a NodeJS script from crashing due to timeout being exceeded

Here is the issue I am encountering: I am attempting to scrape a website's content using NodeJS and puppeteer. Sometimes, my code halts with a Timeout Exceeded error. Is there a way for me to handle this timeout by implementing a function that will e ...

Exploring the use of radio buttons with Bootstrap and AngularJS

Having a radio button like this: <tr> <td>GTS ? </td> <td> <div class="col-md-10 columns"> <ul id="GTSD" class="radio" role="menu" aria-labelledby="menu1"> <label class= ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

Working with promises and Async/Await in Express/node can sometimes feel ineffective

Currently, I am delving into the world of node and express with the aim to create a function that can extract data from a CSV file uploaded by the user. My challenge lies in the fact that the data is being outputted as an empty array before it goes through ...

Accessing the first child node in JsTree

Is it possible to display only the first child of a list using the JStree plugin to create a tree? For example, if I have a list with 5 children, some of which have nested children, I am looking for a way to display only the first child of each <li> ...

Foundation of Worldwide ngResource

In my angular service, I have multiple factories spread across different js files. They all require a common base for queries: 1) Authorization: Bearer token (header) (mandatory after login) 2) AccessDateTime, UserIPAddress (mandatory before login) 3) ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Unable to detect the click event on Bootstrap accordion

I am currently utilizing Bootstrap to populate a table with data and then attempting to capture an accordion show event. My intention is to extract the div id in order to make an ajax call for more information on the respective item. Unfortunately, I have ...

What is the process for the event loop moving into the poll phase?

There is a scenario outlined in the event loop explanation on the Node.js official website. When setTimeout is triggered, and the callback queue for the timer phase isn't empty, why does the event loop move on to the poll phase? The site mentions that ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

Error: Unable to retrieve the name property of an undefined object within a React component that is being used as a child component within another parent component

FundraiserScreen.js // Import necessary components and dependencies; // Import Fundraiser component; const Children = ({ loading, error, fundraiserData }) => { if (loading) // Show skeleton loading HTML if (!error) return <Fundraiser fundraiser={fund ...

Tips for positioning and resizing images within a changing DIV dimension

My DIV element is adjusting its size based on the browser window. Inside this DIV, there is an image that should fill up the entire browser window without stretching out of proportion when the window dimensions change. In addition, I want the image to be ...

Exploring the Synergy Between Play 2.3.x, Webjars, and Requirejs: Unveiling

Queries: Is there a way to streamline the process of setting paths and shims in requirejs for webjars and their dependencies without manual intervention? (Especially for webjars that include a requirejs.config() call?) Does anyone have a straightforward e ...

How to retrieve data from a JavaScript array in a separate JavaScript file

In my checklistRequest.js file, I populate an array and then try to access it in my Termine_1s.html file, which includes JavaScript code. Although I can access the array, when I attempt to iterate through it, only single digits are returned instead of stri ...

Exploring the possibilities of event-driven programming with Java and Javascript?

When performing computations on a server, the client inputs data that is captured through Javascript. A XMLHttpRequest is made to send this data to the server for processing. What happens if the computation takes an hour and the client leaves or switches o ...

Increment the text counter following the uploading of an image file with html format

I have a form in which I am checking the character limit that a user can input into a text field using the 'onkeyup' attribute to update it in real time. Now, I want to achieve a similar function for image uploading. When a user selects an image ...

Using regular expressions to replace text within brackets that have the same type of bracket in between

I am facing an issue with replacing the given string \section{Welcome to $\mathbb{R}^n$} Some content with <h1>Welcome to $\mathbb{R}^n$</h1> Some content The challenge lies in having opening { and } between the curly brackets ...

Storing ng-change event for a checkbox in AngularJS in a valid manner

I have a requirement where I need to handle multiple input checkboxes. The goal is to store the changed checkbox events in an array and then save them when the user submits the changes. <td><input type="checkbox" class="switch" ng-model="each_val ...

Attributes of the host element in Angular 1.5 components

I am seeking a way to customize attributes on the host element for Angular 1.5 components. What is the purpose? I would like to assign a class to a component in order to apply specific styles. For example, if the parent component has display: flex set, ...