The issue arises when trying to access the value that is not defined in the combination of angularjs $

I am currently working on retrieving the Balance value of an ethereum account using the web3 API. My goal is to extract this value and store it in the $scope so that I can access it in my HTML. However, I seem to be encountering an issue where I consistently receive a "value is undefined" error. This problem potentially stems from web3 operating asynchronously, although I cannot confirm this as the root cause of the issue. Presented below is the excerpt of my code:

app.controller('mainController', function ($scope) {
    $scope.showBalance = function(){
        web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc37DB5B451Cb9A8c", 
            function(err, res){
                $scope.balance = res.c[0]
                console.log("This is inside:" + $scope.balance);
            });

        console.log("This is outside:" + $scope.balance);
    };

    angular.element(document).ready(function () {
        $scope.showBalance();
    });
});

While the console log output for "This is inside" displays the correct value, indicating that the operation is successful. The second console log referenced by "This is outside" results in an undefined value.

Answer №1

Unfortunately, I always encounter an issue where a value is undefined. My suspicion is that this may be due to the asynchronous nature of web3, but I cannot say for certain.

Your guess is correct.

Take a look here :

    web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc37DB5B451Cb9A8c", 
        function(err, res){
            $scope.balance = res.c[0]
            console.log("This is inside:" + $scope.balance);
        });

    console.log("This is outside:" + $scope.balance);

The function(err,res) serves as the callback function that is executed once the getBalance() function completes its task.
It's important to note that a callback function declaration does not block the code execution. It only runs after the called function finishes and returns a promise to notify its caller about the result of the task.
So, when the getBlance() function is called, the subsequent code that executes is:

console.log("This is outside:" + $scope.balance);.

However, at this point, the callback function has not been invoked yet.
The line $scope.balance = res.c[0] only gets executed when the callback function is triggered.

In conclusion:

You should remove

console.log("This is outside:" + $scope.balance);
.

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

Conceal or reveal form elements based on input selection

In my current HTML form generated by PHP, I have multiple instances of the following structure: function show(elem, show){ var elements = elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden"); var i; for(i=0; i<eleme ...

What is the best way to eliminate HTML <li> bullets using codebehind?

When working in codebehind, I often create an HTML list using the following method: HtmlGenericControl list = new HtmlGenericControl("ul"); for (int i = 0; i < 10; i++) { HtmlGenericControl listItem = new HtmlGenericControl("li"); Label textLabel ...

Sending data to SOAP API using AngularJS

I've been struggling to send data to a SOAP API but have hit a roadblock. I've attempted various methods but continue to encounter errors when making the API call. The API URL is - and it requires data in XML format like <?xml version="1.0" ...

When the user saves the changes on the pop-up window, the main window will automatically refresh

I currently have a calendar feature that allows users to create, edit, and delete appointments. When a user clicks on the new appointment button, it opens a window above the calendar interface. Once the user fills out the necessary fields and clicks save, ...

What could be causing the state object in React to not be updating correctly? There seems to be a discrepancy between the expanded and

Displayed on the console is a screenshot showing <br><br> I am working with React.js, and the object displayed in the image is an element within an array that is part of the state object. I'm puzzled by what's happening. The object a ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

"Trouble with 3D hexagonal grid in CSS - unable to achieve desired display

In order to create a dynamic Hexagonal Grid using CSS, the objective is to automatically reorganize hexes in a circular or rectangular manner when a new div with a specific class (e.g. 'hexes') is added to the view. Currently, there is a grid wi ...

Endless invocation of AngularJS $http requests

Could someone kindly clarify why the $http request is continuously sending an infinite number of requests to the server in my application? The code snippet provided is causing this issue: (function(){ var app = angular.module("GrahamsSocksProducts", [ ...

I am experiencing an issue where my application, built using NodeJS, Express, and Javascript, is failing to insert form data into the database despite

I am facing a challenge with my app's MVC design pattern where I am unable to insert form information into the corresponding table in the database. Despite installing the body-parser package via npm, the form is not functioning as expected. Can anyone ...

Adding a class to a PHP file using AJAX response

I have been developing a website that features a like button attached to user-generated posts. My goal is to update the like count of a post whenever a user likes it, but I am encountering an issue where the entire post gets affected. Below is the code fo ...

Error: Google Plus Cross-Origin Resource Sharing Issue

I recently developed an AngularJS application that utilizes Google's server-side flow for authentication. The issue arises when my AngularJS app is hosted on one server and the Rest API is hosted on another. After successfully logging in, I encounter ...

Conflict arises between Angular $scope and the file input type

I have been attempting to convert a file into a byte array using AngularJS. The conversion process is successful and I am able to add the byte code and filename to an array ($scope.FileAttachments). However, there seems to be an issue with ng-repeat not wo ...

How to extract column name from query result set using JavaScript in Snowflake database?

When querying in Snowflake with JavaScript inside a stored procedure, we typically receive a Result_set. How can the column names of the output result be retrieved using the JavaScript API? Please note that this inquiry is not about retrieving the values ...

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

Ensuring the canvas fits perfectly within its parent div

I am attempting to adjust my canvas to fit inside a div. // Make the Canvas Responsive window.onload = function(){ wih = window.innerHeight; wiw = window.innerWidth; } window.onresize = function(){ wih = window.innerHeight; wiw = window.innerWidth; } // ...

Compatibility of image maps with browsers and the usage of imagemapster

Currently, I am utilizing ImageMapster to make adjustments to an image map while hovering. However, I am facing challenges with both the image map itself and the ImageMapster plugin. The issues I am encountering are: 1) Despite specifying a height and wid ...

Transforming a request from Angular to PHP through formatting

I am currently working on creating an add function for my Angular application that communicates with my PHP back-end. I am attempting to send data to the server using a transformationRequest, but I am unsure about the correct format that matches the $_POST ...

What is the best way to move data from one HTML link to another HTML link using AngularJS?

<tr ng-repeat="greeting in posts"> <!--<td>{{greeting.user}}</td>--> <td> <div ng-controller="MyCtrl"> <a href="quizlist.js">{{greeting.page_name}} </a> </div> & ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

The functionality of the Toastr "options" seems to be malfunctioning

I am having some trouble with my Toastr notification messages. While the message does display, I seem to be unable to make use of any options that I set. Despite specifying some options, they do not seem to work as intended. $('#editButton').c ...