AngularJS Controller assigns unexpected value to object

While working on a project, I encountered an issue with assigning float values fetched from a REST API using Angular. Instead of correctly assigning the float value, it was being set as 0.

To illustrate my problem clearly, let's consider the following scenario:

$scope.commodities = {
    items: [],
    total: 0,
    total_gst: 0
};

for (var i = 0; i < $scope.output.data.length; i++) {

    var itms = {};
    itms.item_description = $scope.output.data[i].item_description;
    itms.currency = $scope.output.data[i].currency;
    itms.amount = parseFloat($scope.output.data[i].amount);
    itms.ex_rate = parseFloat($scope.output.data[i].ex_rate);
    itms.tax = parseFloat($scope.output.data[i].tax);
    itms.quantity = parseFloat($scope.output.data[i].quantity);
    itms.total_without_gst = parseFloat($scope.output.data[i].total_without_gst);
    itms.gst = parseFloat($scope.output.data[i].gst);
    itms.total_with_gst = parseFloat($scope.output.data[i].total_with_gst);
    console.log(itms.total_without_gst);
    console.log(itms);
    $scope.commodities.items.push(itms); 

}

Here is the data received from the REST API:

{
    "status": true,
    "data": [
        {
            "item_description": "Ocean freight",
            "currency": "USD",
            "tax": 0,
            "amount": 150,
            "ex_rate": 4.42,
            "quantity": 1,
            "total_without_gst": 663,
            "gst": 0,
            "total_with_gst": 663
        },
        {
            "item_description": "DG charges",
            "currency": "USD",
            "tax": 0,
            "amount": 80,
            "ex_rate": 4.42,
            "quantity": 1,
            "total_without_gst": 353.6,
            "gst": 0,
            "total_with_gst": 353.6
        }
    ]
}

A screenshot of the console log can be viewed here.

Answer №1

Due to my low reputation, I am unable to leave a comment at this time. Therefore, I will provide my insights in the form of an answer instead. Based on my analysis of your data and the information available about parseFloat (found here: https://www.w3schools.com/jsref/jsref_parsefloat.asp), it seems that you are passing real float values or numbers, but parseFloat only parses float values from strings. Have you considered assigning the float values directly instead?

Answer №2

It seems like the issue in your situation lies within the for loop you are using. When working with AngularJS, it is recommended to utilize angular.forEach instead of a traditional for loop.

angular.forEach("$scope.output.data", function(object){

});

I have created a fiddle link where I utilized the same object retrieved from the REST API, parsed it, and displayed it on an HTML page.

You can view the solution here: Fiddle Link

If this answer proves helpful, please consider approving it. Thank you!

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

Error: The term "Particles" has not been defined

I'm attempting to integrate code from a website into my project, but encountered an error when the particles failed to run after adding it. I downloaded and installed particle.js from "https://github.com/marcbruederlin/particles.js/issues" for this pu ...

Tips for segmenting text into pages according to the dimensions of the viewport and the font style

Here's a puzzle for you. I have a horizontal slider that loads pages via Ajax, with pre-loading features to maintain smooth performance. Similar to Facebook Billboarding but with a slight twist. By determining the viewport size, I calculate boxSizeX a ...

Convert an object to a custom array using JavaScript

I need to transform the following object: "age": [ { "Under 20": "14", "Above 40": "1" } ] into this structure: $scope data = {rows:[ {c: [ {v: "Under 20"}, {v: 14} ]}, {c: [ {v: "Above 40"}, ...

Determining the size of a custom-typed array in Typescript

Can anyone explain how to find the length of a custom typed array? For example: type TMyArray = IProduct[] interface IProduct { cost: number, name: string, weight: number } So, how can we determine the length in this case: const testArr: TMyArray ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

What is the most effective method for utilizing JSON as a database?

For my upcoming offline mobile web app project, I am considering using JSON to mirror some of my database tables and storing the data in localStorage. (Although Web SQL Database is an option, its future-proofing capabilities are questionable.) Initially, ...

Exclude the node_modules directory when searching for files using a global file pattern

I'm facing some challenges setting up a karma configuration file because I am having difficulty creating a glob that correctly matches my files. Within my lerna repository, there may be node_modules folders inside the packages, and it's importan ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Utilizing the toggle switch functionality in Django with a boolean field implementation

My work_experience model includes an "is_working" field which is set to true when a user is currently employed at a company. I am using a toggle switch on the front end and would like to update the boolean field value for "is_working" with a click. What lo ...

What's Next? Redirecting Pages in Node.js Express after Handling POST Requests

Is it possible to redirect to a different page from a post request? module.exports = function(app) { app.post('/createStation', function(request, response){ response.redirect('/'); //I'm having trouble getting ...

Struggling to generate a cookie through an express middleware

I'm currently working on setting up a cookie for new user registrations in my app to track their first login attempt. I came across this thread which provided some guidance but I'm still facing issues. Below is the snippet of my code: // Middle ...

Can you explain the meanings of <div class="masthead pdng-stn1"> and <div class="phone-box wrap push" id="home"> in more detail?

While working on styling my web pages with CSS and Bootstrap, I came across a few classes like "masthead pdng-stn1" and "phone-box" in the code. Despite searching through the bootstrap.css file and all other CSS files in my folders, I couldn't find a ...

Is there a way to modify the color of the horizontal line within react-native-otp-inputs in the React Native platform?

Is there a way to customize the color of the horizontal line in react-native-otp-inputs for react native? I used react-native-otp-inputs to capture user OTP input, but now I want to change the color of the default black horizontal line to white. You can re ...

Runner for Jasmine specifications and directive template URL

Within my angular application, I have encountered two distinct methods for running unit tests. The initial approach involves running Karma, while the alternative is to utilize the Jasmine spec runner due to its simplicity in terms of debugging. One chall ...

Unable to save screenshot in the report portal while running with WebDriver.io (wdio) execution

In my webdriverio project, the directory structure is as follows: e2e/ utilities/pUtil.js report/screenshot specs wdio.config.js Within pUtil.js file, I have the following code snippet: static takeScreenshot(name, failure = false, test) { const path = ...

Deactivate Mongoose connection in Node.js after completing tasks

Here is a mongoose script I have been using to connect to the local database and perform some operations. However, I am facing an issue with disconnecting the connection after use. const mongoose = require('mongoose'); const db = mongoose.connec ...

Encountering a "Raphael is undefined" error message when working with Treant.js

I need help creating an organizational flow chart using treant.js. Below is my code snippet, but I'm encountering a 'Raphael is not defined' error that I can't seem to solve. Can someone please assist me with identifying the root cause ...

Tips for syncing input field values with mui slider?

Implementing a MUI slider that ranges from a minimum of 8 to a maximum of 255. <Slider value={range} min={minVal} max={maxVal} onChange={handleSliderChange} valueLabelDisplay="auto" /> In addition, displaying input fields to show ...

AngularJS Error Present in Chrome Only

While this code works perfectly in Firefox and IE, it encounters an issue in Chrome. An error occurs at the ".find" line which results in a "TypeError: undefined is not a function". angular.forEach(data, function(data) { pointInfoFactory.ge ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...