sharri58
sharri58

Reputation: 1

Angular.js : Calculating the total of a list of numbers

I need to have a list of numbers display with the total. When someone enters a new number into an input box, the number will be added to the list displayed and the total will change accordingly.

using angular.js...

Upvotes: 0

Views: 308

Answers (2)

Komo
Komo

Reputation: 2138

While itamar's answer works without any doubt, you can write this like this (a bit cleaner in my opinion) :

Controller

Use reduce for total computation :

$scope.numbers = [1,2,3];

$scope.updateTotal = function () {
    $scope.total = numbers.reduce(function (total, number) {
        if (number) {        
            total += number;
        }

        return total;
    }, 0);
};

Markup

<span>{{ total }}</span>
<ul>
    <li ng-repeat="number in numbers">
        <input type="number" ng-model="number" ng-change="updateTotal()">
    </li>      
</ul>

Since you know when the total value should get updated, better use ng-change here so the computation is only done when needed.

On a side note, you can use type="number" in the input so only numbers can be entered.

Upvotes: 3

itamar
itamar

Reputation: 3967

Welcome to StackOverflow - next time please provide some code you wrote yourself. In the meantime - I wrote yours for you :-)

JS in your controller:

$scope.numbers = [1,2,3];
    $scope.getTotals = function(){
    var total = 0;
total = $scope.numbers.reduce(function(prev, curr) {
  return prev + curr;
});
    return total;
    }

HTML:

<ul>
<li ng-repeat="number in numbers"><input ng-model="number"></li>
<li>{{getTotals()}}</li>
</ul>

Upvotes: 1

Related Questions