75441

AngularJS: Summing nested objects from multiple objects

Based in the following table I need to get the total of all subtotals.

I have tried to use the same sumByKey filter but I does't work. Plus, the sum of all subtotals must be based on the result of the filter, it means, If we have two results (two categories) the sum of subtotals must be based on those objects. Any idea?

<strong>html</strong>

<table border="1"> <thead> <tr> <th>#</th> <th>Category</th> <th>Products with quantities</th> <th>Subtotal of quantities</th> </tr> </thead> <tbody align="center"> <tr data-ng-repeat="category in categories | filter:search"> <td>{{$index+1}}</td> <td>{{category.name}}</td> <td>{{category.products}}</td> <td>{{category.products | sumByKey:'quantity'}}</td> </tr> </tbody> <thead align="right"> <tr> <td colspan="3"><strong>Total</strong></td> <td></td> </tr> </thead> </table>

<strong>angularjs</strong>

var app = angular.module("app", []); app.controller("controllerApp", function($scope, $http){ $http.get("categories.json").success(function(data) { $scope.categories = data; }); }); app.filter('sumByKey', function () { return function (data, key) { if (typeof (data) === 'undefined' || typeof (key) === 'undefined') { return 0; } var sum = 0; for (var i = data.length - 1; i >= 0; i--) { sum += parseInt(data[i][key]); } return sum; } });

Answer1:

It can be done with angular also.

Example : http://plnkr.co/edit/zhTtoOjW7J1oumktlvFP?p=preview

HTML:

<table border="1"> <thead> <tr> <th>#</th> <th>Category</th> <th>Products with quantities</th> <th>Subtotal of quantities</th> </tr> </thead> <tbody align="center"> <tr data-ng-repeat="category in filterValues=(categories | filter:search)"> <td>{{$index+1}}</td> <td>{{category.name}}</td> <td>{{category.products}}</td> <td>{{category.products | sumByKey:'quantity'}}</td> </tr> </tbody> <thead align="right"> <tr> <td colspan="3"><strong>Total</strong></td> <td>{{filterValues | sumOfValue:'quantity'}}</td> </tr> </thead> </table>

JS:

// Code goes here var app = angular.module("app", []); app.controller("controllerApp", function($scope, $http) { $http.get("categories.json").success(function(data) { $scope.categories = data; }); }); app.filter('sumByKey', function() { return function(data, key) { if (typeof(data) === 'undefined' || typeof(key) === 'undefined') { return 0; } var sum = 0; for (var i = data.length - 1; i >= 0; i--) { sum += parseInt(data[i][key]); } return sum; } }); app.filter('sumOfValue', function() { return function(data, key) { if (angular.isUndefined(data) || angular.isUndefined(key)) { return 0; } var sum = 0; for (var i = 0; i < data.length; i++) { var value = data[i]; if (!angular.isUndefined(value)) { for (var j = 0; j < value.products.length; j++) { sum += parseInt(value.products[j][key]); } } } return sum; } });

Answer2:

May not be Angular solution. But you can also get total by pure JavaScript.

By keeping a total $scope varaible like this inside your controller

$scope.total = getTotal(data); function getTotal(data){ var total = 0; data.forEach(function(item){ item.products.forEach(function(product){ total += product.quantity; }) }); return total; }

Here is the updated Plunker.

Recommend

  • Add Quantity Selected to Cart Instead of Just Updating
  • UML Class Diagram construction
  • Join 2 tables on dynamically changing column
  • Date cannot be in the future SQL
  • Glassfish XML (or JSON) Response for JAX-RS Object Marshalling Results in HTTP 500 Internal Server E
  • Getting the 'co-ordinates' of a cell using jQuery
  • Eliminate units when using quantities for Python
  • Getting the inner-most row in the embedded tables
  • How can I refresh the entire table sorting cache after dynamic table update?
  • How do one only submit click event (div), when using jquery live function?
  • Trying to total columns for relation datasource
  • TCPDF's getNumLines() is sometimes wrong
  • Play Framework nested form errors missing
  • Selenium - How to skip the record from the Set after the its first occurrence
  • Scrolling News Ticker Jquery - Issues
  • Shopify API CARTS - Changing line_item line_price for price Override
  • How can I make a 100% stacked chart with nvd3?
  • Using extern @class in order to add a category?
  • “A GKScore must specify a leaderboard.”
  • IOS > Open URL in Safari with POST
  • Angular page doesn't refresh after data is added or removed
  • Not able to display correct data in table -AngularJS
  • garbled css name when styling within UiBinder
  • Returning the auto incrementing value after an insert using slick
  • How to open html table in xls on click of a button
  • Plotting densities in R
  • How To Customize ASP.NET Chart Databound To SqlDataSource
  • Update Google Maps traffic layer without page reloading
  • Function calls are not supported. Consider replacing the function or lambda with a reference to an e
  • Sending HTML Form Data to Spring REST Web Service
  • Installing iPhone App to iPhone
  • Meteor helpers not available in Angular template
  • Read a local file using javascript
  • Unanticipated behavior
  • KeystoneJS: Relationships in Admin UI not updating
  • JTable with a ScrollPane misbehaving
  • embed rChart in Markdown
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app