Using orderBy when sorting suggestions jumbles $index for comments


In home.html, listing the suggestions sorted by number of upvotes:

{{ post.title }}
Upvotes: {{post.upvotes}} | See Comments

The suggestions will be sorted by upvotes, but $index corresponds to the order in the original suggestion list as declared in suggestions.js. The link “#!/suggestion/{{$index}}” points to the wrong index. How do I fix this inside home.html? I tried something called “track by $index” but didn’t seem to work.


I have the same problem :wink:
Did You figure it out maybe ?


I got this answer when I asked an advisor, have not had a chance to try it out yet:

Konstantine from Codecademy Pro
Oct 29 (8 days ago)

Ok so what you need to do is modify the data

Maybe give each post object a new property called ID

And use that instead of the $index for your links


Thanks for info :slight_smile:

so…I’m not sure if this the best way to do that :face_with_raised_eyebrow: but it solves the problem:

  1. we need to add new value to our suggestions object (demoSuggestions), for example index
    then use it in link, in home view like this:
    <a href="/#!/suggestion/{{post.index}}"

  2. add to our addSuggestion() function, this value filled with the length of current posts object


I finally got around to implementing this and with your additional suggestions I was able to get it to link to the correct comment, thanks!

However I ran into one strange feature. I numbered my id’s in the posts[] array starting at 1. In home.html when I referenced the link I had to use id-1 to get it to work, as in:

Upvotes: {{post.upvotes}} | See Comments

Do you have any idea why? These href links used in routing are still a bit of a mystery to me.


I had the same problem. The instructions specifically and explicitly tell us to use $index in the home.html file link to comments.

But this doesn’t work, because $index refers to the sorted order within the ng-repeat, not in the actual array. So if you upvote a suggestion so that it moves up, and then click it, or have an unsorted array to begin with, you’ll get the comments for the suggestion that was in that position, before sorting.

This simple fix worked: Instead of {{$index}}, use {{posts.indexOf(post)}} in the home.html file linking to “comments”

No need to modify anything else.

P.S. this is assuming you are using ng-repeat=“post in posts” in that home.html file.