如何获取 ng-repeat 中数组所有索引的第一个元素的总和?
how to get sum of first element of all indexes of array inside ng-repeat?
我想获取 ng-repeat 中数组所有索引的第一个元素的总和。我想声明一个变量,并希望在每次 ng-repeat 迭代中添加值。并希望在最后显示该变量。下面是我的代码。
$scope.test_array = [{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'}];
<tr ng-repeat="x in test_array ">
<td> {{x.qty}} </td>
</tr>
<!-- I want sum of all qty of each index -->
<tr ng-repeat="x in test_array ">
<td>
{{test_array[0].qty + test_array[1].qty + test_array[2].qty + test_array[3].qty and so on... }} </td>
</tr>
Result should be like below.
35
35
35
35
35
35
35
I also want to get that value in javascript.
console.log("first Total" + $scope.first_total); //35
console.log("second Total" + $scope.second_total); //35
And so on...
I read about *ngFor but I am not sure it can be used here or not
js
$scope.test_array = [{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'}];
let newArr = []
for(let i = 0; i < $scope.test_array.length; i++){
for(let key in $scope.test_array[i]){
if(key === 'qty'){
newArr.push($scope.test_array[i][key])
}
}
}
$scope.sum = newArr.reduce(function(a, b){
return a + b;
}, 0);
html
<tr ng-repeat="x in test_array ">
<td>
{{sum}}
</td>
</tr>
我想获取 ng-repeat 中数组所有索引的第一个元素的总和。我想声明一个变量,并希望在每次 ng-repeat 迭代中添加值。并希望在最后显示该变量。下面是我的代码。
$scope.test_array = [{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'}];
<tr ng-repeat="x in test_array ">
<td> {{x.qty}} </td>
</tr>
<!-- I want sum of all qty of each index -->
<tr ng-repeat="x in test_array ">
<td>
{{test_array[0].qty + test_array[1].qty + test_array[2].qty + test_array[3].qty and so on... }} </td>
</tr>
Result should be like below.
35
35
35
35
35
35
35
I also want to get that value in javascript.
console.log("first Total" + $scope.first_total); //35
console.log("second Total" + $scope.second_total); //35
And so on...
I read about *ngFor but I am not sure it can be used here or not
js
$scope.test_array = [{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'},
{qty:5, unit:'each'}];
let newArr = []
for(let i = 0; i < $scope.test_array.length; i++){
for(let key in $scope.test_array[i]){
if(key === 'qty'){
newArr.push($scope.test_array[i][key])
}
}
}
$scope.sum = newArr.reduce(function(a, b){
return a + b;
}, 0);
html
<tr ng-repeat="x in test_array ">
<td>
{{sum}}
</td>
</tr>