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

Deciphering the difference between a null object and the numeral 0

While working on Codewars and attempting to solve a problem, I encountered an interesting question. The task was to create a "toDense()" function that takes a sparse array as input and returns the corresponding dense array. An example test case provided w ...

Guide on displaying several items from Laravel to Vue through the JavaScript filter method?

I need help transferring multiple objects from laravel to vue and filling my vue objects with information retrieved from the database. This is the data received from laravel: https://i.sstatic.net/2Hnk5.png Vue objects to be populated: storeName: {}, ...

Special character Unicode regex for names

After spending the entire day reading about regex, I am still struggling to fully grasp it. My goal is to validate a name, but the regex functions I have found online only include [a-zA-Z], omitting characters that I need to allow. Essentially, I require ...

The AngularJS ng-if directive functions on a variable will only function on the

I'm currently working on updating an old codebase that was written in AngularJS, a framework I am not very familiar with. My task is to implement a spinner that appears when an HTTP request is sent and disappears once the response is received. The sp ...

Conceal a div once the user scrolls to a certain position using vanilla JavaScript

As a beginner in the field of web development, I am currently working on creating a blog website. Code Function - One of the challenges I'm facing is implementing a floating pagination bar that needs to be hidden when a visitor scrolls near the foote ...

Utilizing webpack to import both d3 and d3-cloud libraries

I've been attempting to integrate d3 and d3-cloud (for word cloud) into my AngularJs(v - 1.4) app by using: import d3 from 'd3' import d3Cloud from 'd3-cloud'. However, when trying to use d3-cloud with d3.layout.cloud(), ...

Concealment Based on Surroundings

I'm currently working on implementing a new feature called 'context-based hiding' which involves hiding content based on mouse actions. I've been struggling to figure out how to create this feature and came across a website that has it ...

Sequential execution of multiple useState updates when an update triggers a re-render

Can you explain why the function setPeople is being executed after setFirstName, setEmail, and after the event handler has been exited? const [firstName, setFirstName] = useState(''); const [email, setEmail] = useState(''); const [peopl ...

Using Vue to cycle through an array of objects, and emphasize the chosen item by clicking on it

I have to display an array of objects in the DOM by using map method. Each item has a @click event listener where I want to highlight it with a CSS class 'hover'. The desired functionality is to mimic a menu system where only the clicked item sho ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

Loop through the ng-repeat scope object in AngularJS

Is it possible to create rows of 3 using bootstrap and ng-repeat with data from a scope object without the loop repeating every three times due to ng-if? I am curious if something like <h4> {{yogurt[$index+1].name}} </h4> would work. Below is ...

"An error has occurred stating that the function Factory.function() in AngularJS

I'm a beginner with AngularJS and could use some assistance! My issue involves retrieving JSON data from a URL in a factory function and returning it to the controller. However, I keep getting an error stating that the function doesn't exist. Wh ...

Utilize Python and Selenium to interact with AngularJS dropdown lists for non-select elements

Currently, I am leveraging Selenium to extract information from this website. Upon clicking a button on the page, a dropdown list appears, and my goal is to be able to select different values from this list using my program. Having conducted extensive res ...

A New Approach to Initializing Web Pages in ASP.NET (with a Surprising Twist)

Well, I've encountered quite the puzzling issue with a project I'm working on (it could even make it to the Daily WTF), and I'm hoping for some help in finding a solution. (Apologies in advance for the lengthy explanation...) About a month ...

When transitioning from component to page, the HTTP request fails to execute

I have created a dashboard with a component called userInfo on the homepage. This component maps through all users and displays their information. Each user has a display button next to them, which leads to the userDisplay page where the selected user&apos ...

where is the yarn global registry located?

After updating yarn to point to my custom registry and verifying the changes, here is what I found: $yarn config list -g yarn config v1.22.10 info yarn config { 'version-tag-prefix': 'v', 'version-git-tag': true, ' ...

The array's value fluctuates into a negative without any direct manipulation from my end

In order to work with the $scope.option value, I stored it in a temporary variable and then applied operations on the temporary variable after changing all the values of $scope.option to negative numbers. var app = angular.module('myApp', []); ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Numerous options available in a dropdown menu

I have a Dropdown menu that offers various functions. "Update" option redirects to a page for updating information "Export Form" option redirects to a page for exporting the form Although the current code allows these actions, I am facing an issue with ...