Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jdh
jdh
12,334 Points

AngularJS - Building a Calculate Total function on ng-repeat

Hi Treehouse!

I'm working on an angularjs app and can't figure out why this function won't work.

I have an array of objects (people) that have three stats (created, replied and read). The application is a leaderboard to show the top ten people in specific stats but also overall which is the total.

I have an ng-repeat that iterates over the JSON and renders a new row for each.

I'm trying to create a calcTotal function and this is what I have so far

  $scope.calcTotal = function(){
    var total = 0;
    angular.forEach($scope.users, function(user){
      total = user.created * 10 + user.replied * 5 + user.read * 2;
    })
    return total;
  }

then in the html I have this expression to call the function:

{{ calcTotal() }}

but this prints the same total for all users. Any thoughts?

http://plnkr.co/edit/SwAeBK3dURszEH3Ai07z?p=preview

2 Answers

Keith Kelly
Keith Kelly
21,326 Points

Since you are already running the ng-repeat you can eliminate the forEach loop in your function. In your html pass the user to the function like so:

<span ng-show='discussionsSelect == "total"'> {{ calcTotal(user) }} </span>

Then you can simplify your calcTotal function to:

$scope.calcTotal = function(user){
    return user.created * 10 + user.replied * 5 + user.read * 2;
  }

The totals worked in the Plunker file, but you will still need to deal with the sorting by total points it seems.

jdh
jdh
12,334 Points

Keith Kelly thanks! That works well for the function.

If I want to create a filter to sort the total, would it almost be best to create the function and add a push method to add the the total key to each object then render it? Maybe that way it would be included in the discussionsSelect orderBy filter?

Appreciate the help!