Performing the multiplication of two numbers stored in an object using AngularJS and then calculating the sum

I am currently facing a minor issue with multiplying numbers within an object in AngularJS. My goal is to refactor the code that multiplies two numbers directly in the HTML using AngularJS into a service or factory. Below is the existing code featuring the working HTML (with input as md-text-float from Angular Material), controller, and factory in AngularJS:

HTML:

 <md-text-float ng-repeat="macro in macros"
                    md-theme="deep-orange"
                    label="{{macro.type}}"
                    type="number"
                    ng-model="macro.amount">
  </md-text-float>

<div class="tCalories md-whiteframe-z1" ng-repeat="macro in macros">
       <span class="subtitles">{{macro.type}}</span>
        <div class="macros">{{ macro.amount * macro.multiplier }}</div>
        <md-tooltip>{{macro.tip}}</md-tooltip>
</div>
<div class="tCalories md-whiteframe-z1">
        <span class="subtitles">Total Calories</span>
        <div class="macros total">{{totals() | number: 2}}</div>
</div>

Controller:

app.controller('dataAdd', ['$scope', 'MacroCalculation', function($scope, MacroCalculation) {

$scope.macros = MacroCalculation.macros();
$scope.totals = MacroCalculation.totals();

}]);

Factory:

app.factory('MacroCalculation', function() {

var macros = [
   {'type': 'Protein', 'amount': null,'multiplier': 4,'tip': 'Calories per gram of protein'},
   {'type': 'Carbohydrate', 'amount': null, 'multiplier': 4, 'tip': 'Calories per gram of carbohydrate'},
   {'type': 'Fat', 'amount': null, 'multiplier': 9, 'tip': 'Calories per gram of fat'}
 ];


var getMacros = function() {
    return macros;
};


var calculateTotal = function() {
    var total = 0;
    for (var i = 0; i < macros.length; i++) {
        total += macros[i].amount * macros[i].multiplier;
    }
    return total;
};


var getTotals = function() {
  return calculateTotal();
};

return {
    macros: getMacros,
    totals: getTotals

}

});

While I can successfully retrieve the totals using {{totals()}}, I aim to also move

{{macro.amount * macro.multiplier}}
into a separate function within a factory. I am currently unsure of how to iterate through macros in the factory to perform the same calculation.

Answer №1

Perhaps this information will assist you.

var macros = [
    {
        'type': 'Protein',
        'amount': null,
        'multiplier': 4,
        'tip': 'Calories per gram of protein',
        'total': function() { return this.amount * this.multiplier; }
    }
];

You can apply the same concept universally. If you prefer a single function to manage this, you can use the following:

var singleTotal = function(macro) {
    return macro.amount * macro.multiplier;
}

This approach should resolve the issue at hand.

Additionally, AngularJS provides its own forEach function. Consider implementing the following:

var totals = function() {
    var values = 0; // initialize all variables, it's good practice
    angular.forEach(macros, function(macro, index) {
        values += macro.amount * macro.multiplier;
    });
    return values;
};

Answer №2

Below is the service code provided for you to Copy & Paste:

app.factory('MacroCalculation', function() {

 ....

function calculate(index) {
    //do your math here
} 
return {
    macros: getMacros,
    totals: getTotals,
    calculate: calculate 
}
});

NOTE: Make sure to include this function in your controller as well.

<div class="tCalories md-whiteframe-z1" ng-repeat="macro in macros"> 
    <span class="subtitles">{{macro.type}}</span> 
    <div class="macros">{{ calculate($index) }}</div> 
    <md-tooltip>{{macro.tip}}</md-tooltip> 
</div>

We hope this information proves to be beneficial for 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

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

Issue encountered while attempting to animate a spherical object within a confined space in Three.js

I'm fairly new to three.js and encountering issues while attempting to animate a sphere moving through a space. My approach involves creating a new sphere and using new THREE.Vector3().randomDirection() to set it in motion. The sphere is meant to mov ...

How to incorporate template literals when sending JSON responses in Node.js?

Utilizing express and aiming to return some JSON, I am considering using a template literal. Here is my current approach: resp.status(201).json({ message: "Customer added to database", url: "http://localhost:5000/Customer/" + doc._id ...

Migrate the JavaScript variable created with 'passport' to an Express router

In my quest for authentication, I created the essential passportAuth.js file: module.exports = function(passport, FacebookStrategy, config, mongoose, fbgraph){ passport.serializeUser(function(user,done){ //to make user reference available across pages ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Attempting to get a webGL game downloaded from Unity to automatically enter fullscreen mode

Can someone help me with my Unity webGL game issue? I downloaded it from the internet, but I'm not sure what version of Unity was used to create it. When the game starts playing, it displays in a small canvas along with other elements like the Unity ...

``Is there a way to align components with the same width side by side horizontally

I have a situation where I need to align three components, a radio button and two select fields, on the same row within a container. Currently, they are displaying on separate rows but I want them to be in three columns on a single line. I tried following ...

Instructions for using jQuery to replace the final <a> tag within a specific section

Here is a section that I am working with: <section class="breadCrumb"> <a href="/">Home</a> <span class="divider">&gt;</span> <a class="CMSBreadCrumbsLink" href="/SCCU.Stg/Events-Calendar.aspx">Events Calendar ...

When using the `sendFile` method in Node.js Express, you will notice that the HTML content

Hey there, I'm new to nodejs and trying to create a simple website with two pages. I'm facing an issue where the content of the second file is being rendered as the first one, even though the source inspector in the browser indicates that it&apos ...

How can we stop every tab pane in (bootstrap five) from sharing the same scroll position? Each tab is currently synchronized with the scroll position of the others

In Bootstrap 5, the scroll position remains the same when switching between tabs in the tab pane. Whether moving from tab #1 to tab #2, both tabs are at the identical scroll position, failing to preserve each tab's specific location. <div class=&qu ...

Using jQuery plugins in JavaScript files

I was curious about how to properly import jQuery libraries after installing them from npm. I tried the following methods, but encountered an error: import countdown from 'jquery.countdown'; $.countdown = countdown; $("#hours1").countdown("2020 ...

Using a combination of jQuery and JavaScript to switch image tags between different classes

I'm really struggling with this issue and could use some guidance. Essentially, I have a code that should change the class of an img tag when a user clicks on a div element. Let's take a look at the HTML structure: <li><img src ...

Optimal code structuring for a javascript plugin

Hey there, I came across some intriguing posts on this topic, but I believe it's a very personal question that requires a tailored answer. So, I'm reaching out to ask you: what is the most effective way to organize my code for a JavaScript plugin ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

Issue: The property 'top' cannot be read as it is null

I'm trying to access the top of my footer, but I keep encountering this error message: Cannot read property 'top' of null Here is the HTML code: <footer class="footer" role="complementary" id="myfooter"> </footer> And in jQuer ...

The Facebook app is experiencing issues on Chrome, yet is functioning properly on Firefox

Lately, I've ventured into the world of creating Facebook Apps on heroku. After creating a test app and uploading a page with HTML5, CSS, and Javascript, I encountered an issue where the app wasn't displaying correctly in Google Chrome , but work ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Apply CodeMirror theme and plugins using an HTML attribute

On my website, I have implemented a CodeMirror text area from . <form><textarea id="code" name="code" codemirror-type='lineNumbers: false, styleActiveLine: true, matchBrackets: true;'>CODE HERE</textarea></form> I added ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

Encountered an error injecting 'ngStorage' following the inclusion of the ngStorage file

For this code snippet, I've made sure to include the line that utilizes ngStorage <script src="js/angularjs/ngStorage.min.js"></script> Furthermore, I have injected it into my controller named bookController as is customary .controller( ...