Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible.

I have been given an assignment that requires me to utilize Parse and AngularJS. The task is to display each company from my companies object along with their respective ratings. In Parse, these are stored as separate objects connected by a relation.

Although I have managed to calculate the ratings, I am facing an issue where Angular seems to be overriding the data for the ratings. Instead of displaying each rating, it only shows the last calculated rating. However, when I check the console using console.log(total), the numbers are accurate.

Here's the snippet from my controller responsible for fetching companies:

function getCompanies() {
    new Parse.Query(Companies).find({
        success: function(results) {
            for (var i = 0; i < results.length; i++) {
                results[i].relation("ratings").query().find({
                    success: function(ratings) {
                        var total = 0;
                        for (var o = 0; o < ratings.length; o++) {
                            var stars = parseInt(ratings[o].attributes.stars);
                            total += stars;
                        }
                        total = total / ratings.length;

                        $scope.$apply(function() {
                            $scope.companies = results.map(function(obj) {
                                console.log(total);
                                return {name: obj.get("name"), rating: total, parseObject: obj};
                            })
                        });
                    }
                });
            }
        }
    });
}

In my view, the code I'm using is:

<div ng-repeat="company in companies">
    <h1>{{company.name}}</h1>
    <h3>Rating: {{company.rating}}</h3>
</div>

Currently, if I had two companies with ratings of 2 and 4, Angular would show 4 for both. However, the console will correctly display 2 and 4 separately.

If there are major issues in my code, your feedback is highly valued as I strive to enhance my skills. Thank you for any assistance provided.

Answer №1

Could you attempt implementing a code similar to the following?

success: function(data) {
    for (var j = 0; j < data.length; j++) {
        var item = data[j];
        data[j].relation("reviews").query().find({
            success: function(reviews) {
                //perform total calculation here;
                //var grandTotal = your logic for calculating the total
                //then store the total in the item object
                item.total = grandTotal;
            }
        })
    }
    $scope.$apply(function() {
        $scope.products = data.map(function(element) {
            console.log(grandTotal); // shows accurate results
            return {title: element.get("title"), totalRating: element.total, parsedObject: element};
        })
    });
}

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

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

I encountered an issue in ReactJS where I received a TypeError stating that props.history.listen is not a function

Why is this showing up? I'm using ReactJS and can't figure out what's going wrong. Here is my history.js: import { createBrowserHistory } from 'history' export default createBrowserHistory In my App.js: import React from 'r ...

What is the best way to incorporate Electron browser windows within Angular-CLI components?

How can I use electron browser window inside components in angular-cli if it doesn't accept it? I encountered an error with fs.existsync. Are there any alternative options to integrate electron with angular2 components? var electron = require(&apos ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

FormData enables uploading of several images through distinct fields simultaneously

Looking to upload images to the server before submitting the form? Unable to nest forms, FormData() is being utilized. The form includes a title and 5 images with captions. The goal is to initiate the upload once an image is selected without clicking &apo ...

ng-include once the application has finished loading

Currently, my server is using handlebars to generate the initial HTML page. I would like to include a ng-include in this page to dynamically update the client side. However, every time my application runs, it loads the page and the data-ng-include="templa ...

Secure login system featuring self-contained HTML and Javascript functionalities

I want to create an idle game that will save data on the server instead of using cookies. I am looking for a straightforward method (ideally without using MySQL or PHP) to implement user registration and login functionality using HTML5 and/or Javascript. ...

Populate select2 with the selected value from select1 without the need to refresh the page or click a button

Being a novice in PHP and Javascript, I am looking for a way to populate the "info" select dropdown based on the selected value from the "peoplesnames" dropdown without refreshing the page or using a button. Here's my code: HTML: <select id="peo ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Retrieving components of an array

I am looking to extract elements from an array, then store them in a new array and compare them to another array. The challenge is that I do not want to extract the elements in a specific order. I have tried using the .slice function for extracting element ...

Tips for presenting the retrieved data from the database in a user-friendly format

$ //First step involves running the PHP code that executes the SQL query to retrieve data from the database, storing it in get_row1, and sending it as a response to Ajax$ <?php $connect = mysql_connect("localhost", "root", ""); $data = mysq ...

Clicking on the button will instantly relocate the dynamically generated content to the top of the page, thanks to Vue

Here is some dynamically generated content in the left column: <div v-for="index in total" :key="index"> <h2>Dynamic content: <span v-text="index + ' of ' + total"></span></h2> </div> There is also a butt ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

Steps for exporting various elements from a .vue file

In my Vue project, I am incorporating TypeScript along with Vue. There is a specific scenario where I need to export multiple items from my .vue file. Here's an example of what I want to achieve: // FooBar.vue <template> ... </template& ...

Tips for utilizing the window object in Angular 7

To implement the scrollTo() function of the window object directly, we can use window.scrollTo(0,0). However, when researching how to do this in Angular, I found that many people create a provider as shown below: import {InjectionToken, FactoryProvider} f ...

Finding the correct value in Ajax is proving to be a challenge

In my development of a doctor management system, I am encountering an issue with updating the date field based on changes in the selected doctor. The system includes three form fields: department, doctor, and doctor_time. Through AJAX, I have successfully ...