Ensure that the ng-if directive in AngularJS is used to check if a certain

I'm trying to display a list of elements only if it's not null or empty. To achieve this, I have used an ng-if before the ng-repeat block:

            <tbody ng-if="adsNotEmpty">

                <!-- Start: list_row -->
                <tr ng-repeat="ad in ads">
                    <td>{{$index + 1}}</td>
                    <ad-thumbnail ad="ad"/>
                </tr>                   
                <!-- End: list_row -->

            </tbody>

In my controller, there is code that checks the ads list and sets the adsNotEmpty variable accordingly:

controllers.controller('AdCtrl', ['$scope', 'AdService',
  function($scope, AdService) {
    $scope.ads = AdService.query();
    $scope.adsNotEmpty = ($scope.ads && $scope.ads.length > 0);
  }]);

Even though my RESTful webservice returns an empty response with a HTTP 200 OK status, resulting in adsNotEmpty being false, the ad-thumbnail directive still gets rendered:

Contents of the ad-thumbnail directive:

<td>
AD - {{ad.name}}
</td>

Consequently, "AD -" gets printed on the screen despite the ads list being empty.

The debug output for $scope.ads = AdService.query(); shows:

Array[0]
$promise: Object
$resolved: false
length: 0
__proto__: Array[0]

To resolve this issue, I have made the following changes:

In the controller:

controllers.controller('AdCtrl', ['$scope', 'AdService',
  function($scope, AdService) {

    AdService.query(function(data) {
        $scope.ads = data;
        $scope.adsNotEmpty = ($scope.ads.length > 0);
    });

And in the page:

    <tbody>
        <!-- Start: list_row -->
        <tr ng-repeat="ad in ads">
            <td ng-if="adsNotEmpty">{{$index + 1}}</td>
            <ad-thumbnail ad="ad" ng-if="adsNotEmpty"/>
        </tr>                   
        <!-- End: list_row -->
    </tbody>

Answer №1

It's imperative to pay attention to the log because it reveals that you may not be focusing on the right areas. Before seeking data, make sure you properly navigate through the $promise returned by the Query.

   SocialMediaService.query().$promise.then(function(data) {
       $scope.posts = data;
       $scope.postsAvailable = ($scope.posts && $scope.posts.length);
   });

When using ng-repeat, remember that it loops through the properties of the object obtained from Query, which explains why you might encounter empty instances labeled as POST-.

Answer №2

Give this a shot:

<table-body ng-if="ads.length > 0">

    <!-- Begin: list_item -->
    <tr ng-repeat="ad in ads">
      <td>{{$index + 1}}</td>
       <ad-preview ad="ad"/>
     </tr>                   
    <!-- Finish: list_item -->

</table-body>

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

Utilizing numerous instances of setInterval

I've created a jsFiddle which can be found here: http://jsfiddle.net/dztGA/22/ Main Objective: My aim is to have two independent timers on the same page that can be stopped and restarted either by hovering or manually. The Issue: The problem illustr ...

AngularJS ngRepeat is not complying with the limitTo filter

Currently, I am using ng-repeat to display a list of available supermarket items. These items are fetched in JSON format using $http and stored in $scope.items. The ng-repeat function is working perfectly in displaying all the items. However, my challenge ...

Retrieve the content from a div element and convert it into an integer for mathematical computations

I have a JavaScript function that performs calculations. The final values are stored and displayed in div elements like this: <div id="n3"></div> <div id="n4"></div> <div id="n5"></div> <div id="n6"></div> & ...

Turn off an md-input

I am looking to restrict input under specific conditions, allowing the value to be displayed but not editable. I attempted to use ng disable or ng class, however, it does not seem to be working for me. <div ng-controller="SettingsController"> & ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

What is the best way to append data to the end of an object using ReactJS Hooks?

Looking to set up a checkbox page in ReactJS where data is filtered by checkboxes from different categories using ReactJS hooks. Currently, I am storing the selected checkboxes as an object: { color: 'orange', shape: 'square' } ...

Collections of ajax triumphs

$(".btn_tab").click(function() { var ids = new Array(); $i=0; $(this).ajaxSuccess(function(e) { alert($i); $( ".tab-content .active table tbody tr td a.elusive-align-justify" ).each(function() { ...

HAproxy: unique error handling for OPTIONS and POST requests with 503 errorfile

Our Web application utilizes ajax calls to a backend that operates on a different domain, requiring CORS. The backend setup includes an HAproxy 1.4.22 along with multiple Wildflys running on the OpenShift PaaS. During times when a Wildfly instance is unava ...

Issue with nextElementSibling not applying CSS style

My current issue revolves around a button that is designed to open or close a collapsible div. The HTML structure of this element looks like the following: <div class='outer-collapsible'> <button type='button' class='col ...

An issue arises with Protractor's waitForAngular() function while testing an angular web application on a real device using appium and Chrome

Currently, I am using Protractor to execute end-to-end Cucumber tests for my AngularJS-based web application. I am utilizing Appium to remotely run the tests on a physical Android device. Here are the versions I am working with: Windows 8.1 <a href="/c ...

Unable to update the Angular scope variable directly inside an AJAX call

var request = { "RequestId": $scope.$parent.req_id, "RequestDate": new Date(), "RequestDetails": $scope.$parent.details }; $scope.request_status = "pending"; $.ajax({ type: "POST", url: ...

Switching from jQuery to Vanilla JavaScript and eliminating  

Is there a way to convert this jQuery code into a Vanilla JS equivalent? I've been searching for a solution but haven't had any luck so far. document.querySelectorAll('p').forEach(element => { element.innerHTML = element.innerHTML ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

Issue with second button in Angular Onclick() not been resolved

I'm experiencing an issue with the onClick() methods in my code. There are two onClick() methods present on the UI, but when I click on the second one, it does not call the method while the first one does. I am struggling to figure out why this is hap ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

Are there any available proxy server or Apache modules for converting XML SOAP responses to JSON format upon installation?

Lately, I have been trying to connect to a remote web service using Ajax, but I realized that the service (FedEx Services API) does not seem to support JSON responses. Is there a proxy server or an Apache solution that can help convert the XML/SOAP respo ...

Strategies for troubleshooting asynchronous JavaScript with multiple script loading

Typically, I am familiar with setting breakpoints, inspecting variables, and stepping into functions. The file Default.htm contains numerous scripts and empty placeholders. I prefer to proceed through debugging step-by-step. Unfortunately, setting a brea ...

Optimizing Angular for requireJS deletion

We recently developed an Angular directive that utilizes blueimp-fileupload. Everything seems to be working fine until we decided to optimize our code using requireJs. After running the optimizer, we encountered the following error: Error: cannot call m ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

IntellJ Editor encounters Typescript error

Currently engaged in a project using Angular 1.6 and Typescript. Up until recently, there were no compilation errors to be found. However, I am now encountering some peculiar errors. The code remains unchanged and the application is functioning properly. ...