Calculate the total of an array with the help of the angular forEach function

function dialogController(generate, $scope) {
      $scope.profiles = generate.get_keys('::role');
      $scope.content = {};
      $scope.options = [];
      $scope.servers = {};
      $scope.subs = {};
      $scope.discountList = {};
      $scope.total = {};

      $scope.toggle = function(item, list) {
        var idx = list.indexOf(item);
        if (idx > -1) {
          list.splice(idx, 1);
        } else {
          list.push(item);
        }
      };
      
      $scope.contentList = function(name) {
        $scope.content = generate.get_config('::role::' + name).items;
      };

      $scope.priceMapping = function(subscriptionPrice) {
        var obj = {
          'bronze': [129, 0.5],
          'silver': [165, 0.5],
          'gold': [199, 1],
          'platinum': [265, 1]
        };

        return obj[subscriptionPrice];
      };

      $scope.calculatePrice = function() {
        angular.forEach($scope.options, function(opt) {
          $scope.discountList[opt] = {};
          $scope.discountList[opt].servers = $scope.servers[opt];
          $scope.discountList[opt].subscription = $scope.subs[opt];

          var price = (Math.pow($scope.servers[opt], 0.75)) * $scope.priceMapping($scope.subs[opt])[0];
          console.log(price);
          var hours = Math.round((($scope.priceMapping($scope.subs[opt])[1]) * (Math.pow($scope.servers[opt], 0.75))) * 10) / 10;
          console.log(hours);

          $scope.discountList[opt].price = price;
          $scope.discountList[opt].hours = hours;
        });
        
        var totalPrice = 0;
        var totalHour = 0;
        angular.forEach($scope.discountList, function(item) {
          totalPrice += item.price;
          totalHour += item.hours;
        });

        console.log("Total Price: " + totalPrice);
        console.log("Total Hours: " + totalHour);
      };
    }
    

Answer №1

A special function is available in the controller to automatically calculate the total for you.

<div>Total: {{ getFinalHours() }}</div>

This feature is accessible through the controller section of your code.

$scope.getFinalHours= function(){
    var total = 0;
    for(var i = 0; i < $scope.discountList.length; i++){
        var item = $scope.discountList[i];
        total += item.hours;
    }
    return total;
}

Answer №2

It appears that the question is somewhat unclear, but it seems like this is what you're looking for. At the start, assign the values of totalPrice and totalHours to 0. Use angular.forEach to loop through each object and add it to the variable.

$scope.calculatePrice = function() {
    $scope.totalPrice = 0;
    $scope.totalHour = 0;

    angular.forEach($scope.options, function(opt) {
        $scope.discountList[opt] = {};
        $scope.discountList[opt].servers = $scope.servers[opt];
        $scope.discountList[opt].subscription = $scope.subs[opt];

        var price = (Math.pow($scope.servers[opt], 0.75)) * $scope.priceMapping($scope.subs[opt])[0];
        var hours = Math.round((($scope.priceMapping($scope.subs[opt])[1]) * (Math.pow($scope.servers[opt], 0.75))) * 10) / 10;

        $scope.discountList[opt].price = price;
        $scope.discountList[opt].hours = hours;

        $scope.totalPrice += price;
        $scope.totalHour += hours
    });
    console.log("Total Price : ", $scope.totalPrice);
    console.log("Total Hours : ", $scope.totalHour);
};

HTML

<div> Total Price : {{totalPrice}}</div>
<div> Total Hours : {{totalHour}}</div>

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

Using the attribute to pass an object to a directive and including a variable inside

Is it possible to transfer $scope.data to a directive through its attribute in an Object, without using separate attributes? I would like to achieve the below format with any solution. <custom-directive detail="{index:1, data: {{data}}}"> </custo ...

Load an image dynamically within a JavaScript function

I'm currently utilizing a Javascript photo viewer plugin (found here: http://www.photoswipe.com/). My goal is to dynamically update the photos connected to the plugin as the user swipes through different images. To achieve this, I am using a Javascri ...

PHP Ajax Image Uploading and Storage

Is there a way to effortlessly upload an image and save it in the uploads folder without any page refresh? Not only that, but can we also have the uploaded image displayed on the screen within a designated div section? Unfortunately, I seem to encounter a ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

Exploring JSON parsing using javascript?

I'm currently attempting to work through this webRTC example and have encountered an issue that appears to be minor in nature... The if statement consistently fails to return true, despite the fact that the console message indicates that the property ...

Switching on Closed Captions for HTML5 video while deactivating the standard video controls

I am facing two issues. Whenever I include the track tag in my video element, the default controller of the video pops up, which is causing conflicts with my custom controls. Secondly, I am unable to figure out how to turn closed captions on and off. Thi ...

When I try to make an on-demand revalidation API call on Vercel, it takes so long that it ends up timing

Inspired by Kent C. Dodds, I have created a blog using Github as my Content Management System (CMS). All of my blog content is stored in the same repository as the code, in mdx format. To streamline the process, I set up a workflow that detects changes i ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Why is the type of parameter 1 not an 'HTMLFormElement', causing the failure to construct 'FormData'?

When I try to execute the code, I encounter a JavaScript error. My objective is to store the data from the form. Error Message TypeError: Failed to create 'FormData': argument 1 is not an instance of 'HTMLFormElement'. The issue arise ...

Issue with IE preventing Selenium from triggering Onchange event and causing page to fail to Postback

I am currently working on a web application where selecting an item from one drop-down list triggers the loading of another. However, when using Selenium to automate this process, I have encountered an issue where the page post back is prevented and the se ...

Creating a basic bootstrap modal dialog in ASP.NET MVC: A step-by-step guide

After navigating from the login page, the user clicks on the "ForgotPassword" link and is directed to a separate page where they can fill out a form to request a new password. http://localhost:2350/Account/ForgotPassword Once the user clicks on the "Save ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Update all Vue component imports to include the .vue extension at the end

The Vue CLI has decided to no longer support extensionless imports, causing compatibility issues with certain VS Code extensions like Vetur. In order to address this issue, I require all default component imports from a .vue file to include the file exten ...

Obtaining a URL from a parameter

I have a unique situation with one of my parameters in the routing, as it involves an actual URL. router.get('/api/sitemap/:url', function(req, res) { var url = req.params.url; ... } How can I ensure t ...

Display a sublist when a list item is clicked

I am receiving a JSON object in my view that looks like this: $scope.mockData = [ { "folder": "folder1", "reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }] }, { "folder": "folder2", "reports": [{ "name": ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

Need some assistance in finding a way to input multiple values from multiple buttons into a single input field in JavaScript

Hello, I am looking for a little help with reading multiple values using multiple buttons such as 1, 2, and 3, and displaying the output in the input like '123' instead of just one number at a time. Concatenate numbers with every click. <inpu ...

Having issues with the functionality of the Previous/Next button in my table

I am facing a challenge with my table as I am trying to include previous/next button for users to navigate through it. However, the interaction doesn't seem to be functioning properly, and I suspect that I need to establish a connection between the bu ...