Utilize ng-show/ng-hide to dynamically display messages or content based on the results obtained

One of my functions builds and returns a JSON object like this:

{"message":"No Grupos de MetaDetalles found","entities":[],"breadcrumbs":[],"parent_id":0}

Now, I have an Angular view set up like this:

<table id="example-datatables" class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th class="span1"></th>
            <th><i class="icon-bookmark"></i> Name</th>
            <th><i class="icon-bookmark"></i> Parent</th>
            <th><i class="icon-bolt"></i> Description</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in MetaDetailGroup">
            <td class="span1">
                <div class="btn-group">
                    <a href="#/detailsgroup/edit/{% verbatim %}{{ item.id }}{% endverbatim %}" data-toggle="tooltip" title="Edit" class="btn btn-mini btn-success"><i class="icon-pencil"></i></a>
                    <a href="#/detailsgroup/delete/{% verbatim %}{{ item.id }}{% endverbatim %}" data-toggle="tooltip" title="Delete" class="btn btn-mini btn-danger"><i class="icon-remove"></i></a>
                </div>
            </td>
            <td><a href="javascript:void(0)">{% verbatim %}{{ item.name }}{% endverbatim %}</a></td>
            <td><a href="javascript:void(0)">{% verbatim %}{{ item.parent }}{% endverbatim %}</a></td>
            <td>{% verbatim %}{{ item.description }}{% endverbatim %}</td>
        </tr>
    </tbody>
</table>

I am looking for a way to not display the table#example-datatables if the entities array is empty. Instead, I want to show the error message stored in the JSON under message. Would using ng-show/ng-hide be the solution? If so, how should I implement it?

EDIT 1: The code is no longer functioning

The JSON response remains the same:

{
   "message":"No Grupos de MetaDetalles found",
   "entities":[

   ],
   "breadcrumbs":[

   ],
   "parent_id":0
}

Here's the code snippet from my controller.js:

app.controller('MetaDetailGroupList', ['$scope', '$http', '$location', '$routeParams', '$route', 'noty', function($scope, $http, $location, $routeParams, $route, $noty) {
    var id = "";

    if ($routeParams.id !== undefined) {
        id = '/' + $routeParams.id;
    }

    $http.get(Routing.generate('meta-detail-group-list') + id).success(function(data) {
        if (data.message) {
            $scope.message = data.message;
        } else {
            $scope.MetaDetailGroup = data;
            $scope.orderProp = 'name';
        }
    }).error(function(data, status, headers, config) {
        if (status == '500') {
            $scope.message = "No server connection.";
        }
    });

    $scope.changeUrl = function(id) {
        $location.path('/detailsgroup/list' + '/' + id);
    }
}]);

In my template, I have the following:

<div ng-show="MetaDetailGroup.entities.length === 0" class="alert">
    {% verbatim %}{{ message }}{% endverbatim %}
</div>

<div ng-hide="MetaDetailGroup.entities.length === 0">
    <ol class="breadcrumb"> 
        <li  ng-repeat="breadcrumb in MetaDetailGroup.breadcrumbs">
            <a href="javascript:void(0)" ng-click="reloadCategories(item_breadcrumbs.id)">{% verbatim %}{{ breadcrumb.name }} &#187; {% endverbatim %}</a>
        </li>
    </ol>
</div>

<a class="btn btn-success" href="#/detailsgroup/add" style="margin-bottom: 20px"><i class="icon-plus"></i> Add Detail Group</a>

<table id="example-datatables" class="table table-striped table-bordered table-hover" ng-hide="MetaDetailGroup.entities.length === 0">
    <thead>
        <tr>

            <th><i class="icon-bookmark"></i> Name</th>
            <th><i class="icon-bookmark"></i> Parent</th>
            <th><i class="icon-bolt"></i> Description</th>
            <th class="span1">Actions</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in MetaDetailGroup.entities | orderBy:orderProp">
            <td><a href="javascript:void(0)" ng-click="changeUrl(item.id)">{% verbatim %}{{ item.name }}{% endverbatim %}</a></td>
            <td><a href="javascript:void(0)">{% verbatim %}{{ item.parent }}{% endverbatim %}</a></td>
            <td>{% verbatim %}{{ item.description }}{% endverbatim %}</td>
            <td class="span1">
                <div class="btn-group">
                    <a href="#/detailsgroup/edit/{% verbatim %}{{ item.id }}{% endverbatim %}" data-toggle="tooltip" title="Edit" class="btn btn-mini btn-success"><i class="icon-pencil"></i></a>
                    <a ng-click="confirmDeleteMetaDetailGroup(item.id,item._token)" data-toggle="tooltip" title="Delete" class="btn btn-mini btn-danger"><i class="icon-remove"></i></a> -->
                </div>
            </td>
        </tr>
    </tbody>
</table>

Unfortunately, things are not displaying or hiding as expected. What could be causing this issue?

Answer №1

Check out this jsBin to see my implementation using ng-show and ng-hide

In summary:

<div ng-show="entities.length === 0">
  {{message}}
</div>

<table ng-hide="entities.length === 0" id="example-datatables" class="table table-striped table-bordered table-hover">
<thead>
    <tr>
        <th class="span1"></th>
        <th><i class="icon-bookmark"></i> Name</th>
        <th><i class="icon-bookmark"></i> Parent</th>
        <th><i class="icon-bolt"></i> Description</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="item in MetaDetailGroup">
        <td class="span1">
            <div class="btn-group">
                <a href="#/detailsgroup/edit/{% verbatim %}{{ item.id }}{% endverbatim %}" data-toggle="tooltip" title="Edit" class="btn btn-mini btn-success"><i class="icon-pencil"></i></a>
                <a href="#/detailsgroup/delete/{% verbatim %}{{ item.id }}{% endverbatim %}" data-toggle="tooltip" title="Delete" class="btn btn-mini btn-danger"><i class="icon-remove"></i></a>
            </div>
        </td>
        <td><a href="javascript:void(0)">{% verbatim %}{{ item.name }}{% endverbatim %}</a></td>
        <td><a href="javascript:void(0)">{% verbatim %}{{ item.parent }}{% endverbatim %}</a></td>
        <td>{% verbatim %}{{ item.description }}{% endverbatim %}</td>
    </tr>
</tbody>

Answer №2

To display the table only if there are items in the array, you can use the following code:

<table ng-show="MetaDetailGroup.entities.length" ...

Then, to show a div for a message when there are no items in the array, use:

<div ng-hide="MetaDetailGroup.entities.length" ...

For instance: http://jsfiddle.net/3Nhuk/

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 JSON response from Rails containing multiple lines is not being parsed accurately

I am currently working on a Rails application with a json response using show.js.erb. { "opening": "<%= @frame.opening %>", "closing": "<%= @frame.closing %>"} An issue I encountered is that when @frame.opening contains multiple lines, jQuer ...

What are the steps to implement Vuelidate 2 in a web browser?

Back in the stone age, we used to just drop in a .js file or a CDN reference and start coding. But now things seem much more complicated. I'm trying to use Vuelidate 2 in the browser, but I can't seem to figure it out. I've already done npm ...

Getting the string value from query parameters can be achieved by accessing the parameters and

Currently, I am attempting to retrieve the string value stored within a class-based object variable named question5. The way I am trying to access this variable on the front-end is shown below. axios.get("http://localhost:3001/users/questionaire/?getq ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Retrieve all visible rows using the AngularJS UI-scroll feature

As of now, I have integrated angular-ui/ui-scroll to dynamically load items into a table. Is there a method available to retrieve the visible items that are currently being rendered on the UI using ui-scroll? I have been utilizing adapter.topVisible and ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

What is the best way to adjust the height and width of a div when it comes into view through scrolling?

How can I automatically and frequently change the size of my div when it is scrolled into view? HTML <div id="contact" class="fadeInBlock"> <div class="map"> <div class="pointer"> <div class="dot"></div& ...

What is the best method for calculating the total sum by multiplying the values in an array?

In my current project, I have an array consisting of multiple objects, each containing a property named "amount". My goal is to sum up all these amount values to get the total. Initially, I attempted to use a for loop but encountered an issue where settin ...

The reliability of next router events can sometimes be called into question as they do not always function consistently

I've been working on creating a loading screen for my Next.js project. The issue I'm facing is that sometimes the loading message stays on the screen and doesn't go away even after the page has loaded. I suspect this may be due to the state ...

Zoomsounds: Injecting fresh content into div using data-source attribute

Currently, I am utilizing a javascript audio player called ZoomSounds. It generates circular play button divs and injects content into them using the following code: <div id="ap3" class="audioplayer-tobe skin-minimal" style="po ...

Tips on handling a redirection request following a fetch post request

When communicating with my node server (Express) using fetch to build a Single Page Application (SPA), I have encountered an issue. Upon each request to the server, I validate the session and redirect to a login page if it is not valid. However, I noticed ...

Using Node.js to download and install npm packages from the local hard drive

Is there a way to add an npm package to my Node.js project from my hard drive? It seems like the admin at work has restricted access to npm. I managed to install npm, but whenever I attempt to run "npm install express" in the command line, I keep getting ...

Discovering an Element in jQuery through its ID using Spaces and Variables

My issue involves locating an element within another element using an ID and then adding a class when the ID is hardcoded. For example: var tableId = el.id; $('#' + tableId).find("[id='Checkout On']").addClass('highlight'); ...

What is the mechanism behind range traversal in Javascript?

Exploring the createRange() function and related constructs in Javascript has sparked my curiosity about its practical applications. During my search, I stumbled upon an interesting application called "" that allows users to highlight text with mouse clic ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...

Tips for featuring the latest blog post at the top of a NextJS blog

I have a website built on Next JS with a blog page. The setup is correct, where the /blog page displays content based on slugs. Currently, new blog posts are appearing at the bottom of the page, under older ones. I want to reverse this so that when a new p ...

Utilizing arrays in the label field of Chart.js

Creating a straightforward bar chart using Chartjs 3.x The process involves fetching JSON data from the server, parsing it, and storing specific parts in arrays. See the code snippet below: serverData = JSON.parse(http.responseText); console.log(serverDa ...

What is the best way to inject a custom Angular service into a test in TypeScript without needing to mock it?

I have defined my modules and tests as shown below, but I encounter an issue when attempting to inject ContentBlocksService into the beforeEach(mock.inject((ContentBlocksService)... statement. It shows an error message saying Unknown provider ContentBlocks ...

Failing to complete a field in the form does not generate an error message when submitted [AngularJS]

My code is designed to display an error message if the user clicks the submit button without filling in a field. However, the functionality is currently not working as intended. <form name="loginForm" ng-submit="loginForm.$valid && login()" n ...