我试图得到“金额”的总和' ngRepeat循环中所有对象的键。我还需要根据代表花费该金额的人的另一个密钥来过滤该金额,'名称'。
因此,例如,我想获得Mary和Lewis花费的总金额的单独值。我不太确定正确的方法来实现这一点,我对Angular相对较新。任何帮助将不胜感激。
HTML
<!-- Mary's Items -->
<div class="col-md-4">
<h1>Mary</h1>
<div class="well" ng-repeat="post in posts | filter: {name: 'Mary' } | orderBy: 'created_at':true">
<!-- exit a message -->
<h4>{{post.title}}</h4>
<h3>${{post.amount}}</h3>
<p>{{post.details}}</p>
<!-- delete message -->
<p><a href="javascript:void(0);" class="pull-right glyphicon glyphicon-trash" ng-click="messages.$remove(post)"></a></p>
</div>
</div>
<!-- Lewis' Items -->
<div class="col-md-4 col-md-offset-1">
<h1>Lewis</h1>
<div class="well" ng-repeat="post in posts | filter: {name: 'Lewis' } | orderBy: 'created_at':true">
<!-- exit a message -->
<h4>{{post.title}}</h4>
<h3>${{post.amount}}</h3>
<p>{{post.details}}</p>
<p>{{post.created_at}}</p>
<!-- delete message -->
<p>
<a href="#/edit/{{posts.indexOf(post)}}">edit</a>
<a href="javascript:void(0);" class="pull-right glyphicon glyphicon-trash" ng-click="removePost(post)" ng-confirm-click="Are you sure you want to remove this item?"></a>
</p>
</div>
的JavaScript
spendingApp.controller("SpendingController", function($scope, $firebase,$stateParams) {
//Setup Firebase DB and make available to app
var ref = new Firebase("**Firebase URL**");
var sync = $firebase(ref);
$scope.posts = sync.$asArray();
$scope.whichItem = $stateParams.itemId;
console.log($stateParams);
$scope.itemTitle = $scope.whichItem;
// Add new Item to DB
$scope.addPost = function() {
$scope.posts.$add({
name: $scope.itemName,
title: $scope.itemTitle,
details: $scope.itemDetails,
amount: parseFloat($scope.itemAmount),
created_at: Date()
});
// Clears values;
$scope.itemName = "";
$scope.itemAmount = "";
$scope.itemTitle = "";
$scope.itemDetails = "";
}
});
JSON示例
{
"amount" : 16.04,
"created_at" : "2014-08-17T17:40:18.846Z",
"details" : "upgrade",
"id" : 36,
"name" : "Lewis",
"title" : "Street Fighter Ultra",
"updated_at" : "2014-08-17T17:40:18.846Z"
}, {
"amount" : 19,
"created_at" : "2014-08-17T17:41:08.341Z",
"details" : "",
"id" : 37,
"name" : "Lewis",
"title" : "Webfaction Web Hosting",
"updated_at" : "2014-08-17T17:41:08.341Z"
}
答案 0 :(得分:1)
尝试使用sumFilter
angular-filter模块
例如:
$scope.users = [
{ id: 1, name: 'Ariel', amount: 16.54 },
{ id: 2, name: 'Dan', amount: 13.74 },
{ id: 3, name: 'Ron', amount: 43.90 },
{ id: 4, name: 'Greg', amount: 71.09 },
{ id: 5, name: 'Alex', amount: 84.99 },
];
<强> HTML:强>
<p>{{ users | map: 'amount' | sum }}</p>
<!--Result: 230.26 -->
答案 1 :(得分:0)
我设法找到了一个解决方案,虽然我不认为这是最优雅的方式,但希望有人可以建立在我所能提出的基础之上。如果有人能告诉我如何将getTotal()从3200减去控制器而不是视图,我将非常感激。
JS
// Calculate Total Amount Spent
$scope.getTotal = function(user){
var total = 0;
for(var i = 0; i < $scope.posts.length; i++){
var post = $scope.posts[i];
if (post.name === user) {
total += post.amount;
}
}
return Math.round(total * 100) / 100;
}
HTML
<h4>Remaining Balance ${{ 3200 - getTotal("Lewis") }}</h4>