2017-10-18 121 views
-3

我有象以下陣列如何增加值動態

[ 
    { 
    "name":"x", 
    "type":"deposit", 
    "deposit_amount":100 
    } 
    { 
    "name":"x", 
    "type":"withdraw", 
    "withdraw_amount":10 
    } 
    { 
    "name":"y", 
    "type":"deposit", 
    "deposit_amount":20 
    } 
    { 
    "name":"y", 
    "type":"withdraw", 
    "withdraw_amount":20 
    } 
]  

我需要具有類型爲「存款」和對象「withdraw_amount」對象增加「DEPOSIT_AMOUNT」值的列表中的一個陣列類型爲「撤回」。

我一直在使用採用NG-INIT試圖NG-重複

<th ng-show="$last" ng-init="obj.total.deposit_amount = obj.total.deposit_amount + data.deposit_amount">Amount Collected : {{obj.total.deposit_amount}}</th> 

<th ng-show="$last" ng-init="obj.total.withdraw_amount = obj.total.withdraw_amount + data.withdraw_amount">Amount Withdrawn :{{obj.total.withdraw_amount}}</th> 

當我使用這個我得到了預期的一個,但每次我點擊搜索總價值得到更新。

任何幫助將是Appreciated.Thanks

+0

創建一個函數,調用函數更新存儲與的Array.push一個變量中的數據 – sheplu

回答

1

搞定,像這樣或東西的JavaScript。

var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.data = [{"name":"x","type":"deposit","deposit_amount":100}, 
 
          {"name":"x", "type":"withdraw", "withdraw_amount":10}, 
 
          {"name":"y", "type":"deposit", "deposit_amount":20}, 
 
          {"name":"y", "type":"withdraw", "withdraw_amount":20} 
 
         ]; 
 
    $scope.totalDeposit = 0; 
 
    $scope.totalWithdraw = 0; 
 
    angular.forEach($scope.data, function(obj) { 
 
     if(obj.type == 'deposit') { 
 
      $scope.totalDeposit += obj.deposit_amount; 
 
     } 
 
     else if(obj.type == 'withdraw') { 
 
      $scope.totalWithdraw += obj.withdraw_amount; 
 
     } 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <div>Amount Collected : {{totalDeposit}}</div> 
 
    <div>Amount Withdrawn : {{totalWithdraw}}</div> 
 
</div>

0

var x={}; x.test='xyz'; console.log(x);

- > obj.total.deposit_amount = 'X'