Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!