我从我创建的服务中获取一个JSON数组,其中包含类似于的结果:
[{"_id":"5499aece1d7be6c6a3000001","billName":"Jeep Insurance","startDate":"2014-12-15T00:00:00.000Z","amount":2400,"type":4,"timestamp":"2014-12-23T18:05:02.987Z","__v":0},{"_id":"549bf0597886c3763e000001","billName":"Jeep Leasing","startDate":"2014-12-25T00:00:00.000Z","endDate":"2017-10-14T22:00:00.000Z","amount":16500,"type":4,"timestamp":"2014-12-25T11:09:13.957Z","__v":0}]
现在我想将amount
的总和加到数组中,这样我就可以从我的视图中访问它了。
哪个,看起来像这样:
[{"_id":"5499aece1d7be6c6a3000001","billName":"Jeep Insurance","startDate":"2014-12-15T00:00:00.000Z","amount":2400,"type":4,"timestamp":"2014-12-23T18:05:02.987Z","__v":0},{"_id":"549bf0597886c3763e000001","billName":"Jeep Leasing","startDate":"2014-12-25T00:00:00.000Z","endDate":"2017-10-14T22:00:00.000Z","amount":16500,"type":4,"timestamp":"2014-12-25T11:09:13.957Z","__v":0},{"total":18900}]
但是,如果我在视图中显示{{variablename}}
,则会返回:
[{"_id":"5499aece1d7be6c6a3000001","billName":"Jeep Insurance","startDate":"2014-12-15T00:00:00.000Z","amount":2400,"type":4,"timestamp":"2014-12-23T18:05:02.987Z","__v":0},{"_id":"549bf0597886c3763e000001","billName":"Jeep Leasing","startDate":"2014-12-25T00:00:00.000Z","endDate":"2017-10-14T22:00:00.000Z","amount":16500,"type":4,"timestamp":"2014-12-25T11:09:13.957Z","__v":0},{"total":18900}]
如何直接访问total
值?
如果我尝试,它不会起作用:
{{variablename.total}}
。
答案 0 :(得分:0)
这是您要访问的阵列。
JS档案
$scope.variablename = [{"_id":"5499aece1d7be6c6a3000001","billName":"Jeep Insurance","startDate":"2014-12-15T00:00:00.000Z","amount":2400,"type":4,"timestamp":"2014-12-23T18:05:02.987Z","__v":0},{"_id":"549bf0597886c3763e000001","billName":"Jeep Leasing","startDate":"2014-12-25T00:00:00.000Z","endDate":"2017-10-14T22:00:00.000Z","amount":16500,"type":4,"timestamp":"2014-12-25T11:09:13.957Z","__v":0},{"total":18900}];
您可以使用ng-repeat
迭代数组并打印所需的值。
HTML文件
<div ng-repeat="singleItem in variablename">
{{singleItem.total}}
</div>
答案 1 :(得分:0)
您可以将variablename
传递给totalAmount函数,也可以直接从$ scope获取,迭代每个元素并添加总量然后返回
在视图中
{{totalAmount(variablename)}}
在控制器中
$scope.totalAmount = function(v){
total=0
v.forEach(function(element){
total +=element.amount;
})
return total;
}
或者使用reduce()
$scope.variablename= [{"_id":"5499aece1d7be6c6a3000001","billName":"Jeep Insurance","startDate":"2014-12-15T00:00:00.000Z","amount":2400,"type":4,"timestamp":"2014-12-23T18:05:02.987Z","__v":0},{"_id":"549bf0597886c3763e000001","billName":"Jeep Leasing","startDate":"2014-12-25T00:00:00.000Z","endDate":"2017-10-14T22:00:00.000Z","amount":16500,"type":4,"timestamp":"2014-12-25T11:09:13.957Z","__v":0},{"total":18900}];
$scope.total = variablename.reduce(function(total,element) {
return total+ element.amount;
}, 0);
在视图中
{{total}}
答案 2 :(得分:0)
在我看来,您可以稍微重新调整API的响应:
API输出:
{
"bills" : [],
"total" :<number>
}
标记:
<div ng-repeat="bill in scopeModel.bills">{{bill.billName}}</div>
<div>Total: {{scopeModel.total}}</div>