2017-03-20 53 views
0

我不明白爲什麼下一個代碼不起作用。AngularJs - 吳重複陣列

<div ng-repeat="r in reservations" ng-init="new = r.some_code"> 

<div ng-if="old == new"> 
    <p ng-init="sum = sum + r.cost">{{r.name}} - {{r.cost}}</p> 
</div> 

    <div ng-if="old != new"> 
     <p ng-init="old = new;">Total: {{sum}}</p> 
    </div> 

</div> 

代碼之前,我有一個數組保留類似如下:

reservations = [{name: client 1, some_code = 15, cost: 1000}, 
{name: client 1, some_code = 15, cost: 1000}, 
{name: client 2, some_code = 15, cost: 1000}, 
{name: client 3, some_code = 16, cost: 2000}, 
{name: client 4, some_code = 16, cost: 3000}, 
{name: client 5, some_code = 17, cost: 3000}] 

$scope.old = reservations[0].some_code; 
$scope.sum = 0; 

其結果是我得到的東西,如:

15 - client 1 - 1000 
15 - client 2 - 1000 
15 - client 3 - 1000 
Total: 0 
Total: 0 

我嘗試了一堆的時間,但不同的錯誤的結果。我想要的是顯示每個預訂,如果「some_code」更改,則顯示總數。

我該怎麼做?

注意:數組排序爲some_code

+1

你爲什麼不計算自己的價值觀for循環控制器,而不是poluting與模型計算的看法? –

回答

0

在你的數組中,你有兩個客戶端1,不確定它是否相關。

我認爲把這個求和邏輯移到控制器可能會更好。您可以使用some_code作爲關鍵字創建一個散列值,並將其作爲值。

這將是這個樣子

$scope.reservations = [{name: client 1, some_code = 15, cost: 1000}, 
 
{name: client 1, some_code = 15, cost: 1000}, 
 
{name: client 2, some_code = 15, cost: 1000}, 
 
{name: client 3, some_code = 16, cost: 2000}, 
 
{name: client 4, some_code = 16, cost: 3000}, 
 
{name: client 5, some_code = 17, cost: 3000}]; 
 

 
$scope.totals = {}; 
 
for (var i = 0; i < $scope.reservations.length; i++) { 
 
\t if (totals[$scope.reservations[i].some_code]) { 
 
\t \t totals[$scope.reservations[i].some_code] += $scope.reservations[i].cost; 
 
\t } else { 
 
\t \t totals[$scope.reservations[i].some_code] = $scope.reservations[i].cost; 
 
\t } 
 
}
<div ng-repeat="r in reservations" ng-init="new = r.some_code"> 
 
    <div> 
 
\t <p> {{r.name}} - {{r.cost}} </p> 
 
    </div> 
 

 
    <div> 
 
\t <p> Total: {{totals[r.some_code]}} 
 
    </div> 
 
</div>

+0

這幫了我。謝謝。 –

0

您可以通過some_code渲染預訂,然後有選擇地顯示詳細信息。皮膚貓的方法:JSFiddle