0

Hi I am new to angularjs I have a problem in calculation the sum of the field my code is like this

<div ng-repeat="(key,item) in expenses_data | groupBy: 'category_name'">

  <h4 ng-cloak><i class="fa fa-plus-circle"></i> {{ key }}</h4>

  <div class="form-group" ng-repeat="expn_head in item">
    <label class="col-sm-3 control-label">{{ expn_head.name }}</label>
    <div class="col-sm-2">
      <input type="text" class="form-control input-sm" ng-model="expenses.expenditure_head[expn_head.id]">
    </div>
  </div>

</div>

How do I sum up all the expenses.expenditure_head value entered and put it in the new text field. Is there any function like this:

<input type=text ng-value="{{ sum() }}">

and js

$scope.sum = function() {

  var total = 0;

  for (var i = 0; i < $scope.expenses.expenditure_head; i++) {
    var myValue = $expenses.expenditure_head[i];
    total += myValue;
  }
  return total;
}

json

    [
{
"id":23,
"name":"Agency Commission",
"expenditure_category_id":1,
"category_name":"Main"
},
{
"id":22,
"name":"Bonus to Local Staff",
"expenditure_category_id":1,
"category_name":"Main"
},
{
"id":48,
"name":"Advance for Expenses",
"expenditure_category_id":2,
"category_name":"Other Dept's Budget Exp"
},
{
"id":49,
"name":"Agency TDS",
"expenditure_category_id":2,
"category_name":"Other Dept's Budget Exp"
}

]

Can anyone show me the right direction? I have trying this for a day.

1

1 Answer 1

1

The right way is to do so inside the controller. Create a function call it getSum()

    $scope.getSum = function(){
      var total = 0;
      for(var i = 0; i < $scope.someVar; i++){
        var myValue = $someVar[i];
        sum += myValue;
      }
      return sum;
    };

Then inside your code you do something like

 <td>Total: {{ getSum() }}</td>
Sign up to request clarification or add additional context in comments.

2 Comments

can you please provide me html also
<td>Total: {{ getSum() }}</td> goes inside your template

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.