0

Suppose I am doing this

<div ng-repeat="order in orders">
   <p>order.productname</p>
   <p>order.productvalue</p>

</div>

Is there a way to calculate the total of all the productvalues in the view itself, or do I need to create a function in the controller?Can anyone point me to the right direction please? thanks

1
  • 1
    As far as I know there are no built-in methods, so the simplest way is to define sum function in $scope Commented May 18, 2014 at 20:22

2 Answers 2

2

I would do something like this

In controller

$scope.numberOfItems= function(items){
  return items.length;
}

in template

{{numberOfItems(orders)}}
Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to create a sum function in your controller which will calculate total:

<div ng-repeat="order in orders">
    <p>{{order.productname}}</p>
    <p>{{order.productvalue}}</p>
</div>
<div>
    <p>Total: {{total}}</p>
</div>

Or you can create a filter as in http://cacodaemon.de/index.php?id=55 and have the total sum directly filtered in your view:

<div ng-repeat="order in orders">
    <p>{{order.productname}}</p>
    <p>{{order.productvalue}}</p>
</div>
<div>
    <p>Total: {{orders|sumByKey:'productvalue'}}</p>
</div>

Comments

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.