Was the result from the function not stored in the $scope variable?

Below is the code for my controller:

$scope.mainModel = getReviews({model: mainModelArr[1]});
$scope.compareModel = getReviews({model: compareModelArr[1]});

function getReviews(data) {
    $http.post(url, data)
        .success(function(res) {
            formatReviews(res);
        })
        .error(function(err) {
            console.log("An error occurred: " + err);
        });
}

function formatReviews(data) {
    var review = data[0];
    review.sumReviews = (review.sumReviews / review.ratingAvg).toFixed(0);
    review.sumRecommend = (review.sumRecommend / review.sumReviews * 100).toFixed(1);
    review.ratingAvg = review.ratingAvg.toFixed(1);
    console.log(review); // logs message correctly 
    return review;
}

Even though these functions are running without errors and logging the review variable, it seems like the review variable is not being assigned to either $scope.mainModel or $scope.compareModel.

NOTE: I am aware that it was not assigned because it does not appear in the HTML:

<p>{{mainModel}}</p> 

What mistake did I make and how can I correct it?

Answer №1

When making Ajax requests, they work asynchronously. AngularJS utilizes promises to manage these requests

$scope.mainModel = undefined;
$scope.compareModel = undefined;

getReviews({model:mainModelArr[1]}).success(function(res){
    $scope.mainModel = formatReviews(res);
});

getReviews({model:compareModelArr[1]}).success(function(res){
    $scope.compareModel = formatReviews(res);
});

If you return a post request, it can be handled anywhere you call the getReviews method

function getReviews(data) {
    return $http.post(url, data)
    .error(function(err) {
        console.log("Something went wrong:", err);
    });
}

function formatReviews(data) {
    var review = data[0];
    review.sumReviews = (review.sumReviews / review.ratingAvg).toFixed(0);
    review.sumRecommend = (review.sumRecommend / review.sumReviews * 100).toFixed(1);
    review.ratingAvg = (review.ratingAvg).toFixed(1);   
    console.log(review); // logs message fine 
    return review;
}

Answer №2

When dealing with asynchronous code, it is important to use promises and their then methods instead of simply returning the value:

retrieveData({type: dataArr[1]}).then(function(result) {
    $scope.data = result;
});

retrieveData({type: compareDataArr[1]}).then(function(result) {
    $scope.compareData = result;
});

function retrieveData(data) {
    return $http.post(url, data)
    .success(formatData)
    .error(function(error) {
        console.log("An error occurred: "+error);
    });
}

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

Showcasing numerous pictures from a Json file in ReactJS

I've successfully generated a mockup JSON file that I now need to use for testing a JSON request via axios in a React application. Currently, I am able to log the structure of the JSON file and assign the data to the link. The issue arises when tryi ...

What is the best way to use a timeout function to swap div layers in AngularJS?

Greetings, esteemed members of the Angular Technorati. I bring forth a perplexing yet seemingly simple issue that requires your expertise. My goal is to dynamically switch out a div layer after approximately 11 seconds and display another div layer. How ca ...

Retrieving user input from a designated form using its name in JavaScript

When PHP constructs a form with jQuery and AJAX retrieves it to the current page, all input elements end up having identical names and IDs. While the forms themselves have unique IDs, I am struggling to reference the specific form and its duplicate input I ...

What is the best way in Javascript to retrieve and process multiple stream chunks from a single API request using the fetch() method

I'm dealing with a Node/Express backend where there is a lengthy (10 - 15sec) API call that is responsible for setting up a user's account. To initiate this action from the front-end, I simply use a fetch('my/api/url') GET request. My ...

Update the Vuetify tab to correspond with either the route or query parameters

I am displaying tabs in this manner... <v-tabs v-model="tab" v-on:change="tabbed()" fixed-tabs> <v-tab ripple>Tab A</v-tab> <v-tab ripple>Tab B</v-tab> <v-tab ripple>Tab C</v-tab> // ...

Is it possible to adjust the position/target values of a webkit CSS transition without interrupting its operation

Is there a way to smoothly change the target position or attributes of a running transition without halting it? To illustrate, let's consider this initial animation: -webkit-transition:-webkit-transform 5s ease-in-out -webkit-transform: translate3d( ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

Storing and accessing mixed file types in a web application using either a Blob or File System

Hey there, I am currently in the process of creating a web application that utilizes Spring MVC, Hibernate, MySQL, and AngularJS technologies. As I navigate through this project, I have encountered a specific issue that requires resolution. Imagine a scen ...

What is the best way to delete a subdocument from a main document when either condition x is true or condition y is true?

A subdocument referred to as Bets is embedded into an array of a property on another model called Users. When a user removes a friend, all associated bets with that specific user should also be deleted from the User document (the user who was friends with ...

Using JavaScript, you can move through an array of divs by detecting keypress events

<div id="wrapper"> <img class="seperator selected" src="imgs/character_1.png" tabindex="0" /> <img class="seperator" src="imgs/character_2.png" tabindex="0" /> <br /> <img class="seperator" src="imgs/character_3.p ...

I am facing difficulty in navigating to a different component

App.js import './App.css'; import CreateBug from './CreateBug'; import { BrowserRouter as Route, Routes } from 'react-router-dom'; import Button from '@mui/material/Button'; import { useNavigate } from "react-ro ...

`The activation of Bootstrap list items through embedded spans`

Apologies for the title, I couldn't think of a better way to explain my issue. I have a list-group and I want the buttons to display a specific color when active. However, it seems that the embedded spans are capturing the click event and not registe ...

What is the best way to implement React.memo or useMemo and ensure semantic guarantees?

According to the documentation provided for useMemo: While useMemo can improve performance, it should not be solely relied upon for semantic guarantees. React may choose to recalculate previously memoized values in the future, such as to free up memo ...

Retrieve the value with `eventArgs.get_value()` function to obtain the selected text instead of the ID

When I populate a textbox with autocomplete using the code below, it only returns the selected text and not the rowid. Any idea why alert(eventArgs.get_value()) doesn't return the actual ID of the row in SQL? <script language="javascript" type="te ...

Retrieve the values of two inputs from outside of the event

How can I access the values of two input fields in order to perform calculations as soon as their values are updated? <script> // Accessing the values of the two input fields for immediate calculation based on user input const heightInputEl = docum ...

Solving the issue of jump in vertical motion after a jQuery slideDown animation

Although I am new to Jquery, I managed to create a simple vertical accordion. It fulfills my requirements, but I noticed a slight jerk at the end of the slide down animation. If someone could take a look and provide a solution, it would save me from losin ...

Can I incorporate the name of my web application into the URL using Node.js?

Is it possible to include my web app name in the URL using Node.js? Currently, my web app runs on I am looking to have the pathname /myapp added like so: ...

Is it possible to create an image using jqplot's jqplotToImageStr({}) function on Internet Explorer 8 and earlier versions?

When creating images in jqplot, I often use the jqplotToImageStr({}) function to convert them into a base64 png string for sending to the server. However, I've encountered an issue where jqplotToImageStr({}) returns null in browsers that do not suppor ...

Add middleware to one individual store

When working with Redux, it is possible to create middleware that can be easily applied to the entire store. For example, I have a middleware function called socketMiddleware that connects to a socket and dispatches an action when connected. function sock ...

How can I pass props from a custom _app.js file to the <Navbar> component in Next.js?

How do I go about passing props to a Navbar component that will be included under the Head component? Although I successfully passed props in the index.js page using getServerSideProps, it seems to not work properly in the _app.js file. import ".. ...