Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - sum up numbers using a function and put it in the view

I am trying to create a function that will sum up some numbers from an incoming factory (and some from the client-side in real time), and will put the sum in the view. Totally stuck.

1 - First of all, I do not understand how to display in the view a variable that was assembled within a controller function.

So let's say I have something like:

$scope.total = function() {
    var totalNumber = 0;

}  

How do I get the totalNumber to show in the view?

I assume after I get this, in order to sum up my factory data:

var revenues = [
            { amount: 1254 },
            { amount: 1654 },
            { amount: 33 },
            { amount: 543 }

    ];

I will have to do something like:

 $scope.total = function() {
 var totalNumber = 0;
    for(i=0; i<revenues.length; i++){
      totalNumber = totalNumber + revenues[i].amount
    }

    }  

Is this correct? Will it update in real time if I dynamically change the revenue array?

like image 794
The Whiz of Oz Avatar asked Oct 21 '13 09:10

The Whiz of Oz


1 Answers

As promised, here is a different approach. One that watches the revenues collection and updates a value every time it changes:

<div ng-app ng-controller="SumCtrl">

  Total: {{total}}

  <input type="text" ng-model="newAmount" />
  <button ng-click="add(newAmount)">Add</button>

</div>

And the JavaScript:

function SumCtrl($scope) {

  function total() {
    var totalNumber = 0;
    for(var i=0; i<$scope.revenues.length; i++){
      totalNumber = totalNumber + $scope.revenues[i].amount
    }

    return totalNumber;
  }

  $scope.revenues = [
    { amount: 1254 },
    { amount: 1654 },
    { amount: 33 },
    { amount: 543 }
  ];

  $scope.add = function(value) {
    $scope.revenues.push({ amount: parseInt(value) });
  }

  $scope.$watchCollection("revenues", function() {
    $scope.total = total();
  });

}
like image 57
Brian Genisio Avatar answered Oct 29 '22 21:10

Brian Genisio