Showing a notification message in AngularJS when an object is empty within a repeating element

Currently, I am utilizing AngularJS along with a repeater to cycle through some search results while also implementing a filter for searching purposes.

There are two specific scenarios that I need to address effectively and I am eagerly seeking the most "angular" approach to handle them.

The initial scenario is when there are no search results to display at the start.

The second scenario occurs when the filter is applied, but no search results are returned.

Upon browsing through this resource, I came across a potential solution that could work by creating separate directives for each scenario. However, I am curious to know if there is a way to manage these conditions using native angular directives without requiring additional coding in the controller.

Thank you!

Answer №1

To dynamically display different HTML based on the length of a filtered array, you can utilize the ngSwitch directive in AngularJS.

For a live example, check out this jsFiddle.

Here's the HTML code:

<div ng-app ng-controller="Ctrl">
Search: <input ng-model="searchText">
<div ng-init="filtered = (friends | filter:searchText)">
    <div>{{(friends | filter:searchText).length}}</div>
    <div ng-switch="(friends | filter:searchText).length">
        <span ng-switch-when="0">Nothing was found</span>
        <table id="searchTextResults" ng-switch-default>
            <tr>
                <th>Name</th>
                <th>Phone</th>
            </tr>
            <tr ng-repeat="friend in filtered | filter:searchText">
                <td>{{friend.name}}</td>
                <td>{{friend.phone}}</td>
            </tr>
        </table>
    </div>
</div>

And here's the corresponding JavaScript code:

function Ctrl($scope) {
$scope.searchText = "";
$scope.friends = [{
    name: 'John',
    phone: '555-1276'
}, {
    name: 'Mary',
    phone: '800-BIG-MARY'
}, {
    name: 'Mike',
    phone: '555-4321'
}, {
    name: 'Adam',
    phone: '555-5678'
}, {
    name: 'Julie',
    phone: '555-8765'
}];
}

Alternatively, you can also apply the $filter("filter") function directly on the friends array in the controller to simplify the HTML markup.

Answer №2

Here is a convenient syntax to display a message when no data is found:

<p ng-show="(friends | filter:searchText).length==0">Oops! No results found</p>` 

Make sure to replace 'friends' with the appropriate JSON object.

Answer №3

Using ngRepeat provides the ability to assign a name to the items that remain after applying all the filters. This assigned name can then be used to display the desired content.

<p ng-repeat="friend in friends | filter:searchText as displayedFriends">
    {{friend.name}}
</p>
<p ng-if="!displayedFriends.length">
    No results found
</p>

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

In JavaScript, an HTTP request file includes a JavaScript variable

I am currently working on a Node.js project that involves making an HTTP request to fetch a JavaScript file. For example, let's say we have a file named a.js: var a = 'i am a.js'; var b = 'please convert me to js'; Here is the a ...

The initial component update

I am new to React and currently working on a main component that includes a child component with a table. Upon mounting, I make an API request to fetch data which is then displayed in the table. My issue arises when, after the initial update of the child c ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

What is the best way to include numerous attributes to an element using JavaScript?

Attributes can be included within a string in the following format: let attr = ' min="0" step="5" max="100" '; or let attr = ' min="2019-12-25T19:30" '; and so on. Is there a function available ...

axios does not distinguish between response and error in its return value

I have created a React component that contains a function called onFormSubmit. This function calls another function from a separate component, which in turn makes a POST request using axios. I want the ability to return a response if the POST request is su ...

Encountering an undefined response while attempting to validate a form using Ajax

I am encountering an issue with my form validation in JavaScript before submitting through PHP. The textarea fields are returning as undefined and the checkboxes are not sending any data. Being relatively new to JavaScript and PHP, I am unsure of what coul ...

Encountering difficulty accessing the object from the props within the created method

After retrieving an object from an API resource and storing it in a property, I encountered an issue where the children components were unable to access the object inside the created method. This prevented me from assigning the values of the object to my d ...

AJAX: Building a Robust Single Page Application with Enhanced Security

Currently, I am developing a web/mobile application using AJAX. This app consists of 4 pages: the login page and three protected pages that are only accessible to logged-in users. My plan is to implement the Single Page Application pattern, where all 4 pa ...

Bringing in a selection of functions as an object using ES6 imports

functions.js export const setA = () => {...} export const setB = () => {...} export const setC = () => {...} component.js import {setA, setB, setC} from 'functions' export class componentOne extends React.Component { constructor(p ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

The form submits automatically upon loading the page with empty input fields

I recently created a form on my website located at . Initially, the form functioned correctly and the PHP script executed as expected. However, I am now encountering an issue where every time I load the page, a popup message appears indicating that the for ...

What is the best way to include additional items in a list?

Trying to add a new element of an array to the list while updating one property (id) by making it 1 more than the length of the array has resulted in strange outputs. Each new object added causes all elements to have values of array.length + 1. Various at ...

"Receiving an 'undefined index' error when attempting to post in Ajax with

Need help with sending data from client to server using AJAX in PHP. I am facing an issue when trying the following code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascrip ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

The object[] | object[] type does not have a call signature for the methods 'find()' and 'foreach()'

Here are two array variables with the following structure: export interface IShop { name: string, id: number, type: string, } export interface IHotel { name: string, id: number, rooms: number, } The TypeScript code is as shown below ...

How can I use jQuery UI to slide a div, while also smoothly moving the adjacent div to take its place?

Wishing you an amazing New Year! I am looking to create a smooth sliding effect for a div when a button is clicked. I want the adjacent div to slide alongside it seamlessly, without any clunky motions or delays. Currently, the adjacent div only moves afte ...

What is the best way to exclude a field from a Joi schema?

I've defined a Joi schema for a User with the following rules: const userRules = Joi.object({ name: Joi.string().pattern(new RegExp('^[A-Za-zÁÉÍÓÚáéíóúãõÃÕâêôÂÊÔ ]+$')).required(), email: Joi.string().email().requ ...

Guide to transmitting and managing a JSON document utilizing JavaScript

When working on the server side, I receive a simple JSON file via REST that contains various IDs. Here is an example: [ { "_id": "5825a49dasdasdasd8417c1b6d5", } "_id": "dfsdfsdf4960932218417c1b6d5", } "_id": "23434344960932218417c1b6d5", },] To handle t ...

Firefoxx effortlessly glides divs across the screen as if they were images

Below is the HTML, CSS, and JavaScript code all in one document for testing: <style type="text/css"> #slider_container { width: 200px; height: 30px; background-color: red; display:block; } #slider { width: 20px; height: 30px ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...