Saya ingin mendapatkan jumlah elemen pertama dari semua indeks array di dalam ng-repeat. Saya ingin mendeklarasikan variabel dan ingin menambahkan nilai setiap iterasi ng-repeat. dan ingin menampilkan variabel itu di akhir. Di bawah ini adalah kode saya.

$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
1
priyank patadiya 6 Juli 2020, 04:26

1 menjawab

Jawaban Terbaik

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>
1
Sunny 6 Juli 2020, 05:18