Reputation: 14283
I'm working with angular, and i need to be able to display an array length but without using ng-repeat
.
here's the scenario:
I have default.json:
{
{ ...
"data":
[{
"name":"Test",
"errors":
[
{"id": 1,"level": 2,"details": {...}},
{"id": 3,"level": 1},
{"id": 5,"level": 1},
{"id": 5,"level": 1},
....
],
},
{
"name":"Test",
"errors":
[
{"id": 1,"level": 2,"details": {...}},
{"id": 5,"level": 1},
....
],
}
],
....
}
}
then I've created myData from the controller, so that I can do something like ng-repeat="data in myData"
and i can use it properly.
Now, here's the question:
I Need to have a recap of all the errors, a sum of all the errors in the objects.
I tried to do something like this:
<span ng-repeat="data in myData">
<i ng-repeat="error in data.errors">{{error.length}}</i>
</span>
and nothing was printed. So I tried:
<span ng-repeat="data in myData">
<i>{{data.errors.length}}</i>
</span>
and the result was:
4 2 0 0 0 0 0
and it makes sense, because my first object as 4 errors, my second one 2 and so on...
But what I'd like to see is only: 6, as there are 6 errors in total.
How can I get only one value that sums all the errors from all the objects I've got without having to use ng-repeat
(I think I don't need it there)
Hope this question is clear enough, thanks for your help.
Upvotes: 0
Views: 111
Reputation: 1115
A possible solution is to use reduce, so you can use the reduce like this
var result = array.reduce((prev, curr) => prev + curr);
if the array is [4,2,0]
the result
it will be 6
so a possible solution will be on the markup call a function in scope
{{arraySum(data.errors.length)}}
and the function will be
$scope.arraySum= function(array) {
return array.reduce((prev, curr) => prev + curr);
}
EDIT for this edit we will use the function map
markup
{{totalErrors()}}
code
$scope.totalErrors = function(){
if ($scope.myData)
return $scope.myData.data.map(function(o){ return o.errors.length})
.reduce((prev,curr) => {return prev + curr})
}
I have created a plunker from what i understand that is your data you can see it working here
Here is a plunker that simulates the delay of an ajax request using $timeout. It uses ng-cloak on markup to prevent displaying raw data.
Upvotes: 1
Reputation: 2327
use this code in the controller (updated for the promise)
function countErrors(myData) {
$scope.totalErrors = myData
.map(function(data) {
return data.errors.length; })
.reduce(function(acc, errorsLenght){
return acc += errorsLenght }, 0)
}
$scope.myData.$promise.then(countErrors)
Upvotes: 1
Reputation: 740
You should do in this way in your controller
var sum=0;
for(var i=0;i<$scope.MyData.length;i++)
{
var error=[];
error=$scope.MyData[i].errors;
sum=sum+error.length;
}
alert(sum+'');
Upvotes: 1