Reputation: 8663
I have a simple ng-repeat that displays a list of values (financial income). How can i calculate the average from this list?
<div ng-repeat="data in MyData">
{{ data.income }}
</div>
<div>
Average:
</div>
Which displays:
11
14
8
9
21
10
2
1
5
13
Thanks
Upvotes: 1
Views: 12879
Reputation: 88
In HTML
Average: {{calculateAverage(MyData)}}
Code
$scope.calculateAverage = function(MyData){
var sum = 0;
for(var i = 0; i < MyData.length; i++){
sum += parseInt(MyData[i], 10); //don't forget to add the base
}
var avg = sum/MyData.length;
return avg;
};
Upvotes: 5
Reputation: 1581
You'll have to write a function which takes as argument the integer array and returns the average.
Most suggestions here assign the function to the $scope in your controller, however, I would create a $filter for reusability across your app as a utility.
(function(angular) {
function average($log) {
return function(array) {
if (!angular.isArray(array) || array.length === 0) {
$log.error("Expect array.");
return;
}
var sum = 0;
angular.forEach(array, function(value) {
if (!angular.isNumber(value)) {
$log.error("Expect number.");
return;
}
sum += value;
});
return sum / array.length;
};
}
angular
.module("yourAppName")
.filter("average", ["$log", average]);
})(angular);
You can now inject $filter anywhere in your Angular code and use the function by the "average" namespace.
angular
.module("yourAppName")
.controller("yourCtrl", ["$filter", "$scope", function($scope, $filter) {
$scope.MyData = {
income: [], // your integer array
average: $filter("average")($scope.MyData.income);
};
}]);
Or right in the HTML:
<div ng-repeat="data in MyData">
{{ data }}
</div>
<div>
Average: {{ MyData | average }}
</div>
Upvotes: 4
Reputation: 3056
I don't think this is related to AngularJS. You need to create a function who calculates your average and then :
<div ng-repeat="data in MyData">
{{ data.income }}
</div>
<div>
Average: {{ myAveragingFunction(MyData) }}
</div>
Upvotes: 3
Reputation: 4107
You can use Alasql library for calculation averages and other data processing.
This is a code of controller:
function MyCtrl($scope) {
$scope.MyData = [{income:1000}, {income:2000}];
$scope.avgIncome = function() {
return alasql('SELECT VALUE AVG(income) FROM ?',[$scope.MyData]);
};
};
And HTML:
<div ng-repeat="data in MyData">
{{ data.income }}
</div>
<div>
Average: {{avgIncome()}}
</div>
See this example at jsFiddle.
Upvotes: 0