Angular JS is patient when waiting for asynchronous requests to complete

Once upon a time in a factory

  httpFactory.factory('setFavorability', function($http){
        return{
            Like: function(id){
                return $http.get('http://localhost:51265/Film/Like/' + id);
            }
        }
    });

In the realm of controllers

$scope.thisLike = function(id){
        setFavorability.Like(id).then((response) => {
            $('.favorability-count').text(response.data);
        })
    }

All seems well and good. Except for my confusion around binding to element classes. I wish to go about it this way

<button  
                        class="fa fa-thumbs-up like" 
                        ng-click="favorability=thisLike(film.FilmId);"></button>
                <div>
                    <span ng-class="{'low-rating':favorability < 0}" 
                          class="favorability-count">{{ favorability }}</span>
                </div>
                <button  
                        class="fa fa-thumbs-down dislike" 
                        ng-click="favorability=thisDisLike(film.FilmId)"></button>

So, initialize a local variable in the markup and assign it from the returning method. However, I struggle to get the correct value.

I attempted this approach

    $scope.thisLike = function(id){
      let v = 0;
        setFavorability.Like(id).then((response) => {
            v = response.data;
        })
      return v;
    }

Alas, the method returns prematurely without awaiting the value retrieval. Thus, I receive 0.

Answer №1

First things first, why even bother with jQuery in this scenario? There's absolutely no need for it!

"However, keep in mind that the method returns immediately."

This behavior is actually correct since your Promise (the http call) operates asynchronously.

If you're looking for a solution, try implementing the following:

$scope.rating = 0
$scope.thisLike = function(id){

    setRating.Like(id).then((response) => {
        $scope.rating = response.data;
    })
}

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 SVG with an integrated script to automatically adjust to the available space within different browser

I am attempting to develop a self-contained SVG document that automatically adjusts its size and centers itself when loaded in a web browser. It's important to note that this is not referring to embedding an SVG within an HTML document. Below is the ...

My Discord bot powered by Discord.js is being unresponsive to commands

Hello, I'm facing a major issue with my command handler that I've been struggling with for a while now. The problem is that my bot doesn't respond when I try to use a command. I've tried various methods from YouTube but none of them see ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

How can one easily implement a countdown timer in an Ionic 3 app?

Easily create an Ionic3 timer set to 2 minutes that displays countdown like 1:59, 1:58, and finally reaches 00:00. Once the timer hits 00:00, a block of HTML content will be shown. ...

Encountering an issue with executing Google API Geocode in JavaScript

I'm having trouble printing an address on the console log. Every time I run the code, I encounter an error message that reads: { "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or &ap ...

When navigating using the next and back buttons, the active state in Angular is automatically removed

Looking for some assistance with my quiz app setup. Each question has True/False statements with corresponding buttons to select T or F. However, when I click the next/back button, the active class is not being removed from the previous selection. As a beg ...

How can JavaScript be used to rearrange the placement of DOM elements?

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="boxes"> <div class="red" style="width: 300px; height: 300px; color: red"></div> <div class="blue ...

Issues with reloading when passing POST variables through Ajax requests

I have a button with the id #filter <input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" /> Below is the Ajax script I am using: <script> $(document).ready(function(){ $('#filter').click(function() ...

Angular examine phrases barring the inclusion of statuses within parentheses

I require some assistance. Essentially, there is a master list (arrList) and a selected list (selectedArr). I am comparing the 'id' and 'name' from the master list to those in the selected list, and then checking if they match to determ ...

Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application. Requirement: User must be authenticated User can read/write their own data entries User can read data with "visibility" field set to "public" User can rea ...

The Truffle test encounters an issue: "Error: Trying to execute a transaction that calls a contract function, but the recipient address ___ is not a contract address."

Every time I run truffle test in the terminal, I encounter the following error message: Error: Attempting to run a transaction which calls a contract function, but the recipient address 0x3ad2c00512808bd7fafa6dce844a583621f3df87 is not a contract address. ...

Navigating through child elements within a div using JavaScript

I recently coded a div using this snippet... let sidebarBox = document.createElement("div"); sidebarBox.id = "sidebarBox"; ...and then I created a second div like so... let sidebarAd = document.createElement("div"); sidebarAd.className = "sidebarAd"; B ...

Preloading Vue dynamic routes for optimal performance

Currently dealing with a challenge on my Vue project and could use some help. I'm looking to prerender specific dynamic routes when I navigate to a particular route within the application. On the /works route, there's a list of items displa ...

Establishing a user session with Node.js

I am new to the world of node.js and JavaScript in general. I have a piece of code that currently handles login functionality by checking if a user exists in a MYSQL database. This part is functioning correctly. Now, I wish to improve this feature by crea ...

Error in Node.js: Using `import` token incorrectly

I am having trouble figuring out what the issue is. Node v5.6.0 NPM v3.10.6 This is the code snippet: function (exports, require, module, __filename, __dirname) { import express from 'express' }; The error message reads: SyntaxError: Une ...

Formatting numbers in JavaScript objects

I am looking to iterate through an array of objects and convert the string values into numbers. Here is a sample scenario: I have data in a format similar to the variable provided below. When passing this array to a kendo chart, it seems to have trouble r ...

Having trouble with PHP's JSON encoding functionality?

Take a look at my code for validating with angular and php. I need to check the validity of this form <form ng-submit="dk()"> <label for="">Name</label> <input type="text" name="name" ng-model="formData.name"> {{errorName}} &l ...

Switching the destination for routing within a program

I'm trying to update the route location in AngularJS using $location.path within a function, but I'm encountering some difficulties. app.controller('globalCtrl', function($scope, $route, $location){ $scope.changePath = function(newPat ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

Getting the value of elements with the same id in JavaScript can be achieved by utilizing the getElement

When I click on the first delete link, I want to display the value from the first input box. Similarly, when I click on the second delete link, I want to show the value from the second input box. Currently, it is always showing the value from the first del ...