Showing information on the webpage obtained from parsing the data

I have successfully retrieved data from the offers table and displayed it on both the console log and the HTML page after resolving async issues with the Q.promise. Now, I am attempting to add data from the users table to the page as well. While I can see the data in the console, it is not appearing on the page. Here is the code snippet from the offers.service:

    this.getAllOffers = function () {

    var Q = $q.defer();
    console.log('getAllOffers called');

    //all offers filter is selected
    this.allOffersFilter = false;

    var offers = Parse.Object.extend("Offer");
    var exchanges = Parse.Object.extend("Exchanges");
    var users = Parse.Object.extend("User");

    var query = new Parse.Query(offers);
    var userQuery = new Parse.Query(users);

    var results = [];

    query.descending("createdAt");
    query.limit(4);

    userQuery.find().then(function(users) {
        for (i = 0; i < users.length; i++) {
            foundUsers = users[i];

            query.find().then( function(offers){
            for(i = 0; i < offers.length; i++){
                found = offers[i];
            var result = {};

            result.date = found.get("createdAt");
            result.price = found.get("price");
            result.status = found.get("accepted");
            result.lastName = foundUsers.get("lastName");
            result.companyName = foundUsers.get("companyName");

            console.log(result.companyName);
            console.log(result.price);
        }
    });
    results.push(result);
  }
  Q.resolve(results);
    });
  return Q.promise;
  };

Next, here is the relevant HTML code:

    <!--List of offers-->
    <div class="col-md-3">
        <h4>List of offers</h4>

        <div ng-if="offersList">
            <div ng-repeat="offer in offersList">
                <div class="offer card">
                    <div>{{offer.username}}</div>
                    <div>{{offer.companyName}}</div>
                    <div>{{offer.date}}</div>
                    <div>{{offer.price}}</div>
                    <div>{{offer.status}}</div>
                </div>
            </div>
        </div>
        <div ng-if="!(offersList)">There are no offers</div>
    </div>

Finally, here is the component code:

angular.module('offersPage')
.component('offersPage', {
    templateUrl: 'pages/offers-page/offers-page.template.html',
    controller: function(AuthService, PageService, OffersService, 
$scope) {
        // Functions for offers-page

        // Check if user is logged in and verified on page load
        AuthService.userLoggedin(function(loggedIn, verified) {
            if(!verified) {
                PageService.redirect('login');
            }
        });

        this.$onInit =  function() {
            OffersService.getAllOffers().then(function(offersList) {

            $scope.offersList = offersList;
            });
      }
    }
});

Thank you in advance for any assistance!

Answer №1

When you resolve $q before results is filled, your list will be empty.

I'm not familiar with Parse server, but if userQuery.find().then is an async function, then you may need to relocate Q.resolve(results); inside it, or perhaps within query.find().then.

Answer №2

When using an ng-if directive in AngularJS, the element is removed and reinserted as a child scope. To prevent scope issues, remember to add $parent to any child element within an ng-if block. Check out the example below. It's also a good practice to include track by $index when working with repeats. Notice that you don't need to use $parent in the repeat block since it refers to the defined offer.

Code:

<div ng-if="offersList">
            <div ng-repeat="offer in $parent.offersList track by $index">
                <div class="offer card">
                    <div>{{offer.username}}</div>
                    <div>{{offer.companyName}}</div>
                    <div>{{offer.date}}</div>
                    <div>{{offer.price}}</div>
                    <div>{{offer.status}}</div>
                </div>
            </div>
        </div>

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

Is there a way for me to retrieve the widths of all child elements within an HTML document?

I have been working on a JavaScript (jQuery) function to calculate the maximum width of all child and children's-child elements within a specific div element. Here is the code I have written so far: function setBodyMinWidth(name){ var max = 0; $(nam ...

A guide to building your own live HTML editing tool

I'm currently developing a PHP website that allows users to enter text into a textarea, and have the input displayed in a table in real time for a preview of the result. I am seeking guidance on how to make this feature possible. I have come across w ...

Eliminating 'related' elements with jQuery

I am facing an issue with deleting items in a list. The list contains two types of products, product-x and product-y. Whenever I delete one type of product, I want the equivalent product of the other type to also be deleted. I have tried different approac ...

The only time an effect is triggered is when calling the same function simultaneously with different parameters in React's useEffect

Introducing my latest creation - the "CommonStyleGenerator" component. This nifty tool generates a simple style object with properties such as height, width, and background color. The best part is, whenever there is a change in any of the text fields withi ...

Element Proxy

I decided to experiment and see how a library interacts with a video element that I pass to it. So, I tried the following code: const videoElement = new Proxy(document.querySelector('video'), { get(target, key) { const name = typeof ...

Implementing jQuery autocomplete on dynamically generated fields post page load

I have successfully implemented jQuery UI Autocomplete to fetch data from a DB and populate a form dropdown. However, I am faced with the challenge of adding more form fields dynamically that also need to have the autocomplete feature applied to them. Is ...

Set a maximum limit for the number of checkboxes that can be selected

If there are 10 checkboxes on a page, I am searching for a specific behavior: Use a variable called maxSelections to control the maximum number of selectable checkboxes Once maxSelections is reached, disable the other checkboxes on the page Even after re ...

Next.js is causing an error by not recognizing the document variable

While diving into the world of next.js, I encountered an interesting challenge. In my project, I came across this puzzling error. The culprit seemed to be a module called Typed.js, which threw me off with a peculiar message: Server Error ReferenceError: d ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

What steps should I follow to set JSONP as the dataType for a request in an Angular $http service?

I have a good understanding of how to use jQuery's $.ajax: $.ajax({ url: //twitter endpoint, method:"GET", dataType:"jsonp", success:function() { //stuff } }); Is there a way to set the JSONP datatype for an angular $http service reque ...

Angular UI Bootstrap Pagination Error: [$compile:nonassign] encountered due to pagination issue

I have encountered an issue with the Angular Bootstrap UI's pagination directive in my simple implementation. I cannot seem to figure out the error despite using the relevant code snippets: <ul> <li ng-repeat="todo in filteredIdeas"> ...

When the @change event is triggered, Vue data objects do not exhibit reactivity

Trying to figure out why the msg and show data parameters are not updating when triggered by @change. To ensure that these parameters are only updated upon successful file upload, I placed them inside the lambda function of onload: reader.onload = functio ...

Are the arrays' values not matching up?

I have a challenge where I need to verify if two values from two separate arrays are equal. One value is retrieved from MySQL, and the other is obtained from the Facebook API. The user's location is represented by $UserHomeTown[1], while the friend&a ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

Showing the name of a class

Hello everyone, I have a piece of JavaScript code that generates HTML buttons when the page loads. The button attributes are fetched from a database through an ASP page. Everything is working fine except for displaying the class attribute - it shows as u ...

If there are no visible layers, OpenLayers will not recognize zoom scroll events

I have observed that when all OpenLayers.Layers are set to invisible, I lose the ability to zoom in and out using the mousewheel. Although I can still use the OpenLayers.Control.Zoom buttons, the mouse wheel functionality is disabled. Is there a way to de ...

Unusual behavior in sorting values with JavaScript

I have spent hours trying to figure this out, and the only conclusion I can come to is that when there are 14 elements to sort, it doesn't function properly, but with thirteen elements, it works perfectly. My goal is to sort DIV elements based on the ...

Is there a way for me to detect click events on Windows notifications?

Currently, I am attempting to send notifications through the node-notifier package. The goal is for a click on the notification to lead to a specific link. However, I am encountering difficulties in listening to the click event - the events provided by the ...