如何在Angularjs中动态添加值

时间:2013-11-12 13:05:49

标签: angularjs

我想在AngularJS中动态添加JSON元素的值。下面是我想要显示它的HTML标记:

<tr>  
  <th class="right"> Ending Value<span class="subVal">:</span></th>
</tr>
<tr>
  <td class="right">$21,50,868.06</td>
</tr>

现在对于这个结束值,我希望它应该是json下面retailAcctTotalBalance个元素的总和:

"acconnts": [{
    "userName": null,
    "retailAcctNumber": "574436368",
    "retailAcctTotalBalance": 0.0
}, {
    "userName": null,
    "retailAcctNumber": "101215858",
    "retailAcctTotalBalance": 2118639.38
}, {
    "userName": null,
    "retailAcctNumber": "101900352",
    "retailAcctTotalBalance": 32228.68
}, {
    "userName": null,
    "retailAcctNumber": "574435165",
    "retailAcctTotalBalance": 0.0
}]

2 个答案:

答案 0 :(得分:1)

最简单的方法:

在你的html文件中,你可以这样做:

<td class="right">{{ sum }} </td>

而且,在你的控制器中:

$scope.sum = 0;
$scope.accounts = { /* your json data */ };
angular.forEach($scope.accounts, function(acc, index) {
    $scope.sum += acc.retailAcctTotalBalance;
});

答案 1 :(得分:0)

一种方法,在范围内添加一个功能,从模型中输出您想要的内容

$scope.total=function(){
   var total=0;
   angular.forEach($scope.accounts, function(account) {
      total += acc.retailAcctTotalBalance;
    });
    return total;
});

标记:

<td class="right">{{ total() }} </td>

现在每当对数据进行更新时,角度观察者将运行摘要周期,在每个摘要周期,它将评估标记中找到的范围函数

另一种方法是观察数据并在变量发生变化时更新变量

$scope.total=0;
$scope.accounts={ /* data*/}

$scopw.$watch('accounts',function(newVal,oldVal){
   if(newVal != undefined)
   $scope.total = getTotal();
})

function getTotal(){
   var total=0;
   angular.forEach($scope.accounts, function(account) {
      total += acc.retailAcctTotalBalance;
    });
    return total;
});

标记:

<td class="right">{{ total }} </td>