Scope challenges with making multiple rest calls in Angular.js

As a beginner in Angular.js, I am facing an issue with $scope not receiving additional value from one of two $resource rest calls. Below is the code snippet:

controller: function ($scope, $modalInstance, $route) {
            $scope.server = {}

            $scope.submit = function () {
                //AddNewServer is a $resource service
                AddNewServer.post($.param({
                    'name': $scope.server.name,
                    'ip': $scope.server.ip,
                    'port': $scope.server.port
                }));

                //ServerStats is a $resource service
                ServerStats.postServerStats(function success(data) {
                    $scope.server.bytesIn = data.returnValue.bytesIn
                }, function err(err) {
                    console.log("Error: " + err)
                })

                $modalInstance.dismiss('cancel');
                $route.reload()

                //BELOW LOG RETURNS Object {name: "asd", ip: "asd", port: 2} NO bytesIn
                console.log($scope.server) 
            }

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
                $route.reload()
            };
        }

I need help on how to include bytesIn from my other service call into my server object. I understand it might be a simple fix, but I appreciate any assistance during this learning phase. Thank you.

Answer №1

Make sure to keep in mind that your postServerStats() call is asynchronous, meaning that the success function may not have been executed by the time you reach the console.log($scope.server) statement.

To avoid this issue, place the console.log($scope.server) inside your success function, right after assigning $scope.server.bytesIn.

You might want to consider adding more functionality within the postServerStats() callback for better control over the asynchronous behavior.

Alternatively, explore using Angular promises for a more structured approach.

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

I am interested in utilizing props to send a variable to the view

Looking for assistance with passing the variable tmp_sell to my view. Here is the code: <p @tmp_sell="getTmpSell" >?</p> <input ref="q_subtotal" placeholder="Subtotal" @tmp_sell="getTmpSell" i ...

Guide on enabling a new input field in React when a dropdown option is selected by a user

I'm attempting to show an additional input field when the user selects "Other" from the dropdown menu. I have implemented a state for the input field that toggles between true and false based on the selected value from the dropdown. However, I am enco ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

Tips for creating a mock for a function that yields a JSX Element

I am facing a problem where I have a function that returns a JSX Element. Here is a snippet of the code: myFunction.jsx const myFunction = (props) => { // ... do something with props return <MyElement {...newProps} /> } // MyElement.j ...

Ways to conceal an item by considering the size of a different element

I have a question about displaying content within a div element. I want to show a "show more" button only if the content inside the div exceeds a max height of 530px. Otherwise, the button should remain hidden. Here is the code snippet I'm using: Ja ...

"Enhancing Collaboration with NextJs Multi-Zones' Unified Header

Currently, I have two applications named admin-shell and delivery-management, both of which are being managed using Multi Zones in NextJs. These applications share a common header with navigation links, but I am encountering difficulties navigating betwee ...

Top method for managing missing sub-documents in MongoDB query outcomes

I've seen this question asked in various forms before, but I'm seeking the most efficient way to manage query results without relying on multiple if statements. Imagine I need to locate a product (sub-document) within a package (document) Packa ...

Issue with JavaScript: Flag set to false does not halt the simple animation

My goal is to initiate animations when the mouse is pressed down and then immediately halt them once the mouse is released. Upon pressing the mouse, I set a flag to true which triggers the animation of the corresponding button that was clicked. However, t ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Whenever I attempt to click on a Teaxarea, it automatically collapses and prevents me from typing my comments

After crafting my code on this link, I created three directives, each responsible for collapsing certain elements. Upon running the code, you will notice two panels where clicking on the address collapses it, and clicking on the comment also collapses it. ...

The request for an advertisement was successful, however, no ad could be displayed as there was insufficient ad inventory available. Please handle the situation appropriately with the

Using react-native, I am trying to incorporate ads into my app but encountering an error. Despite attempting various solutions, nothing seems to work. It appears that the issue may lie with the AdMob Android SDK. While I have reviewed SDK videos related to ...

"Exploring the process of looping through an array of JavaScript objects and showcasing a List Selector on the Google Assistant app with the help of

After extensively researching all the available documentation at https://developers.google.com/actions/assistant/responses In the documentation for the "List Selector," all the examples provided involve static and predetermined data. In a real-world scen ...

What is the best way to integrate properties subsets into your classes?

In my code, I am working with 3 classes ... class1 { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; this.toClass2 = function() { // TODO: return this as an instance of class2; // the conversion would remove the un ...

Having trouble with jQuery validation: Seeking clarification on the error

I have implemented some validations on a basic login page and added jQuery validation upon button click. However, the code is not functioning as expected. I have checked the console for errors but none were displayed. Here is the code for your review: ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

Guide to displaying a component within the Vue instance

I am currently in the process of developing a Nuxt module that will not interfere with the main Nuxt application. My approach involves creating a separate Vue instance and mounting it as a child node under the body element, similar to a child node to the _ ...

Shadow and Quality Issues with SVG Images

I have designed a unique SVG image with intricate details and a decorative frame, enhanced with shadowing effects. Unfortunately, after importing this SVG into a react-native application using the react-native-svg library, I noticed that the shadow around ...

Encountering an error while including ngmin in the r.js build file

Currently, I am attempting to utilize ngmin with requirejs's r.js as outlined in a guide found here. Unfortunately, I have encountered issues and cannot seem to make it work. Despite installing both ngmin and requirejs globally and locally using npm, ...