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.