如何动态添加数组的值

时间:2017-10-18 15:12:54

标签: javascript angularjs

我有一个包含值列表的数组,如下所示

[
  {
    "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  
  }
]    

我需要添加" deposit_amount"类型为"存款"和" withdraw_amount"类型为&#34的对象;撤回"。

我尝试过使用ng-init使用ng-repeat

 <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>

当我使用它时,我得到了预期的一个,但每次点击搜索时总值都会更新。

任何帮助都会得到感谢。谢谢

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

- &GT; obj.total.deposit_amount ='x'