I've created this filter:
app.filter('totalItems', function() {
return function (input) {
var total = [];
input.forEach(function (value, key) {
if (total.length > 0) {
for (var i in total) {
if (input[key].descripcion == total[i].descripcion) { // 'descripcion' is an String
total[i].cantidad += 1; // 'cantidad' is a Number
} else {
total.push(input[key]);
}
}
} else {
total.push(input[key]);
}
});
return total; // It's returning just an empty array. Why?
}
});
For this view:
<table>
<tr>
<th>Descripcion</th>
<th>Precio</th>
<th>Cantidad</th>
</tr>
<tr ng-repeat="(key, value) in tempCart | orderByPriority | totalItems">
<td class="ar"> {{ value.descripcion }} </td>
<td> {{ value.precio | currency: 'BsF.' }}</td>
<td> {{ value.cantidad }} </td>
</tr>
Using this controller:
app.controller('cartController', ['$scope', '$firebase', function(sp, fb) {
var userSessionRef = new Firebase('https://XXXXX.firebaseio.com/development/user_sessions/uid/');
sp.tempCart = fb(userSessionRef);
}]);
(The reference looks like this)
The idea of the filter is to sum similar items and return an array with the total; if there are three objects that have 1 apple, the filter should return one object with 3 apples. But none of my tries have been successful.
What could be wrong?
Thanks in advanced.
EDIT:
Thanks to this, I've changed the filter for a simplest one:
app.filter('totalItems', function() {
return function (input) {
var output = [],
found,
x = 0,
y = 0;
for ( x = 0; x < input.length; x++ ) {
found = undefined;
for ( y = 0; y < output.length; y++ ) {
if ( input[x].id === output[y].id ) {
output[y].cantidad += 1; // This line is causing a "$digest() iterations reached" error.
found = true;
}
}
if ( !found) {
output.push( input[x] );
}
}
return output;
}
});
The function works great but not the filter; it's producing this error:
Error: $rootScope:infdig Infinite $digest Loop
I haven't found a way to solve it even though I've read this explanation... Honestly, I don't know what could I do.