簡體   English   中英

如何獲取ng-init和ng-repeat中的總和-angularjs

[英]How do I get the total sum in ng-init and ng-repeat - angularjs

ng-init和ng-repeat angularjs有問題

我試圖循環字段率以獲取總數

例如這是我的桌子

nane +++++++ id +++++++ 費率

+++++++++ 1 +++++++ 3

+++++++++ 2 +++++++ 3

+++++++++ 3 +++++++ 3

+++++++++ 4 +++++++ 3

這是我的代碼。

<table>
<tr>
  <td>name</td>
  <td>rate</td>

</tr>
<tr ng-repeat="item in videos">
<td>{{item.name}}</td>
  <td ng-init="videos.total.rate = videos.total.rate + item.rate">{{item.rate}}</td>

</tr>
<tr>
  <td>Total</td>
  <td>{{videos.total.rate}}</td>

</tr>

加在一起時,我得到的結果是3333,而不是12

這是問題所在

<td ng-init="videos.total.rate = videos.total.rate + item.rate">{{item.rate}}</td>

如果我將其更改為數字,則效果很好。

<td ng-init="videos.total.rate = videos.total.rate + 3">{{item.rate}}</td>

您的幫助會很棒。

在控制器中嘗試類似這樣的操作。

JS

   $scope.RateTotal= 0;
    for (var i = 0; i < data.length; i++) {
    $scope.RateTotal= $scope.RateTotal + data[i].rate;
   } 

HTML

  <p>{{RateTotal}}</p>

上面的選項更好,但是如果要使用ng-init,請使用類似以下的內容。

<table ng-init="RateTotal = 0">
 <thead>
<th>Rate</th>
 </thead>
<tbody>
<tr ng-repeat="item in videos">
<td ng-init="$parent.RateTotal= $parent.RateTotal + item.rate">{{item.rate}}</td>
</tr>
<tr>
       <thead>
            <tr>
            <th>Total</th>
            <th>{{RateTotal}}</th>
            </tr>
       </thead>
</tr>
</tbody>
</table>

聚苯乙烯

可以濫用此指令在模板中添加不必要的邏輯量。 ngInit只有少數適​​當的用法,例如別名ngRepeat的特殊屬性,如下面的演示所示; 以及通過服務器端腳本注入數據。 除了這幾種情況,您應該使用控制器而不是ngInit來初始化作用域上的值。 -ngInit

將此邏輯移至控制器中。 那就是它的目的。 該視圖應顯示數據。

現在,您必須擔心如何將字符串轉換為整數,並用angular必須解釋為javascript的語言編寫4倍以上的代碼。

您在此處添加的復雜性將很有趣。


但您可能想繼續做錯,在這種情況下應該可以使用: <table ng-init='videos.total = {"rate": 0}'>

定義一個過濾器以計算總數:

app.filter('calculateRateTotal',function(){
    return function(input){
        var total = 0;
        angular.forEach(input,function(value,key){
            total = total+value.rate;
        });
        return total;
    };
});

HTML:

<td ng-bind="videos | calculateRateTotal"></td>

經過10個小時的運氣失敗后,我才設法做到這一點。 變得非常簡單。

這是代碼。

在控制器中添加

$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.videos.length; i++){
    var item = $scope.videos[i];
    total += (item.rate*1);
}
return total;   }

和HTML

<table>

        <tr>
            <th>Rate</th>
        </tr>


        <tr ng-repeat="item in videos">
            <td>{{item.rate}}</td>

        </tr>           
        <tr>              
            <td>Total: {{ getTotal() }}</td> 
        </tr>

    </table>

謝謝大家的幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM