我正在尝试使用AngularJS计算总金额。 想要计算上图中突出显示的总支出金额。 任何帮助将不胜感激。
<body ng-app="nombre">
<div class="container">
<div class="row">
<div class="col-12">
<form class="row" id="nombre">
<div class="input-group mb-3">
<input type="text" class="form-control col-9" id="Spentfor" name="Spentfor" placeholder="Spent for">
<input type="text" class="form-control col-3" id="SpentAmount" name="SpentAmount" placeholder="Spent Amount">
<div class="input-group-append">
<button id="add" class="btn" type="submit">Add</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="container" ng-controller="budgetCtrl">
<div class="row list" ng-repeat="kasu in panam">
<div class="col-6"> {{ kasu.title }} </div>
<div class="col-6 text-right total">
{{ kasu.spent | currency:"₹" }}
</div>
</div>
<div class="row">
<div class="col-6"> Total Money spend </div>
<div class="col-6 overalltotal"> {{ getTotal() }} </div>
</div>
</div>
</body>
我的JS:-
var nombre = angular.module('nombre', ['ngRoute', 'firebase']);
nombre.controller('budgetCtrl', ['$scope', 'money', '$firebaseObject', function($scope, money, $firebaseObject){
money.then(function(data){
$scope.cash = data;
// $scope.pisa = data.desktop;
});
var ref = firebase.database().ref();
$scope.panam = $firebaseObject(ref);
var pa = $scope.panam;
$("#nombre").submit(function() {
$(this), console.log("Submit to Firebase");
var Spentfor = $("#Spentfor").val(),
SpentAmount = $("#SpentAmount").val(),
total = { title: Spentfor, spent: SpentAmount};
alert(total);
return ref.push().set(total).then(function() {
$("#Spentfor, #SpentAmount").val("");
});
});
$scope.getTotal = function(){
// edit here
}
}]);
nombre.factory('money', ['$http', function($http){
return $http.get('budget.json')
.then(function(response){
return data = response.data;
}, function(error){
alert('error');
});
}]);
我试图将其完成。
$scope.getTotal = function(){}
以上数据是从Firebase调用的。我正在尝试计算使用AngularJS的总金额。任何帮助将不胜感激。
答案 0 :(得分:0)
根据您在HTML模板中显示的数据,这应该可以:
$scope.getTotal = function(){
let total = 0;
$scope.panam.forEach(p => {
total += parseFloat(p.spent);
});
return total;
}
迭代所有项目(panam
,然后将spent
编号添加到通过功能total
发送回的getTotal
中。
答案 1 :(得分:0)
您可以致电getTotal
并通过pa
let total =0;
$scope.getTotal = function(obj){
obj.forEach(function(item){
total += parseFloat(item.spent)
})
}
var pa = $scope.panam;
$scope.getTotal(pa)
答案 2 :(得分:0)
您可以遍历并添加到总数中
$scope.total = 0;
money.then(function(data){
$scope.cash = data;
// if cash is array of object
$scope.getTotal();
});
$scope.getTotal = function(){
$scope.cash.forEach((val) => {
$scope.total += val.spent;
})
}