Ways to calculate the sum of a property within an object contained in a dynamically generated array in AngularJS

I've been struggling with this problem for a while now - I can't seem to find a solution. The issue is that I have an empty object that gets filled with products when clicked on (ng-click="AddProduct(product)"). Each product in the array has a property called subtotal, which is always an integer. My goal is to update the total every time a product is added to the array. Additionally, after all the products are added, the user should be able to add or subtract either a fixed amount or a percentage from the total (like adding extra charges or applying a discount). To achieve this functionality, I created a total function as shown below:

$scope.total = function () {

    var total = 0;

    angular.forEach($scope.orderContent.products, function (s) {

        total += parseFloat(s.subtotal);

        if ($scope.orderContent.totals.extras.ServiceCharge) {

            total = total + $scope.orderContent.totals.extras.ServiceCharge;

        }
        if ($scope.orderContent.totals.extras.ServiceChargePercentage) {

            total = (total / 100) * $scope.orderContent.totals.extras.ServiceChargePercentage + total;

        }

    });

    total = total.toFixed(2);

    return total;
};

The problem I'm facing is inconsistency - sometimes the above code works perfectly (such as when I finish adding a product and then adjust the total), but other times it doesn't work as expected (for instance, when I add a value, delete it, and add another one, the original value seems to linger and gets added together with the second value).

What could I possibly be missing here?

EDIT: I've created a Plunker to showcase the issue.

http://plnkr.co/edit/oiwsnO?p=preview

Answer №1

Is it recommended to utilize ng-bind instead of ng-model in this scenario?

<span ng-bind="calculateTotal()"></span>

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

An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach: Below, you'll find a list of 12 images: <img id="img1" src=""> </img> <img id="img2" src=""> </img> <img id="img3" src=""> ...

Angular 7 offers seamless synchronization for horizontal scrolling in a unique way

Can anyone provide guidance on how to achieve synchronized horizontal scrolling in an Angular project? I found a solution at the following link, but it uses jQuery code. Synchronized scrolling using jQuery? ...

Is jQuery validation compatible with mobile phone numbers?

Is there a way to verify an Iranian mobile phone number using jQuery with the input:text? Iranian mobile phone numbers follow a specific numeral system, such as: 091- --- ---- 093[1-9] --- ---- 092[1-9] --- ---- 090[1-9] --- ---- Here are some example pr ...

The Marvelous jQuery Star Rating Plugin

Is it feasible for users to display a label (e.g. "very poor") while using the jQuery Star Rating Plugin, similar to how it is shown on this different star rating? ...

Troubleshooting the pushstate back function in HTML5 and jQuery

In my code, I have implemented an ajax call to load content dynamically. I am now looking to add a deeplinking effect, and after researching, I discovered that only raw coding can achieve this. Here is what I have implemented so far: jQuery("#sw_layered_c ...

having trouble setting up create-react-app

I recently started learning about the React ecosystem and just installed Yarn ➜ WebstormProjects yarn --version 0.23.2 Following the documentation, I then proceeded to install create-react-app globally with Yarn ➜ WebstormProjects yarn global add ...

"Utilizing Google Charts DataTable to easily adjust column number based on data dynamics

Struggling with managing JavaScript objects... Currently, I am working on generating a Google Chart based on user selections. The process involves two multi-select lists that construct an object as shown below: $('option:selected', $('#slC ...

Add some hues to the icons

I am a beginner when it comes to CSS and jQuery. My goal is to color in an icon, similar to Instagram's heart icon which turns red when double-tapped. Currently, I am using Font Awesome for this purpose. However, I am struggling to fill the color as ...

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

Ways to access a hidden button inside div elements using Protractor without an ID

I am struggling to access and click a button within nested div classes in my protractor project. Embarking on this new protractor project for work has brought me to a point of confusion. I have encountered a button deeply embedded within div classes that ...

New properties are not being successfully added to Passport Profiles

I am currently utilizing Passport OAuth2.0 with Google as my provider and encountering an unusual syntax issue. The structure of my authentication setup is as follows: passport.use(new GoogleStrategy({ clientID: GOOGLE_CLIENT_ID, clientSecret: GO ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

The checkbox in angular js is failing to be marked as selected

<tr ng-repeat="languages in samln"> <td> <span>{{languages.emplang}}</span> </td> <td> <input type="checkbox" name="checkbox1-" id="sp1" value="false" style="margin-left:40px;" ng-model="languages ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...

Displaying values from a JSON array in a BIRT report

I'm facing an issue with printing JSON values from a database column in my Birt report. It seems to only display the last line of the JSON array, rather than all the lines before it. Below is the code for my dynamic text field: var phone = JSON.parse ...

JavaScript: Adding elements to an array is ineffective

I'm currently working on a function to loop through an array and perform specific actions based on whether an item already exists: If the item is found, remove it If the item is not found, add it to the array However, I've encountered a proble ...

How to Fetch Data Using jQuery AJAX in PHP Without Page Refresh

I am trying to prevent the page from refreshing when clicking on a select option, but when I do so, the data does not get updated. Here is the code: echo "<form name='frmtopdevotees' method='post' action='topuser_load.php&apos ...