Angular - summarize numbers with a function and put it in a view

I am trying to create a function that sums some numbers from an incoming factory (and some from the client side in real time) and puts the amount in a view. Completely stuck.

1 - First of all, I don’t understand how to display in a view a variable that was assembled in a controller function.

So, let's say I have something like:

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

How do I display totalNumber in a view?

I assume that after getting this, to summarize the factory:

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

I will need to do something like:

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

It is right? Will it be updated in real time if I dynamically change the revenue array?

+6
source share
3 answers

As promised, there is a different approach. One that oversees the revenues collection and updates the value each 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 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(); }); } 
+8
source

There are several approaches to solving this. If you need the total() function, it will look like this:

 <div ng-app ng-controller="SumCtrl"> Total: {{total()}} <input type="text" ng-model="newAmount" /> <button ng-click="add(newAmount)">Add</button> </div> 

And here is the code:

 function SumCtrl($scope) { $scope.revenues = [ { amount: 1254 }, { amount: 1654 }, { amount: 33 }, { amount: 543 } ]; $scope.total = function() { var totalNumber = 0; for(var i=0; i<$scope.revenues.length; i++){ totalNumber = totalNumber + $scope.revenues[i].amount } return totalNumber; } $scope.add = function(value) { $scope.revenues.push({ amount: parseInt(value) }); } } 

The total() function will re-evaluate whenever the area changes (a lot). The best approach is to keep track of revenues changes and update the static value ... I will also post this answer.

0
source

Here plunker

There are several ways to do this, and your controller may look different depending on how the data looks from your factory.

Edit: Several good answers were posted here when I wrote. This is similar to Brian's first approach.

0
source

Source: https://habr.com/ru/post/956399/


All Articles