5

I'm using Angular JS and Google Places API to build an web app.

I have an ng-repeat which is currently being ordered by "rating" descending(orderBy:'-rating'). So it will list x places from the Google Places API JSON file in the descending order based on the rating.

HOWEVER, items/places that don't have a rating are classed as null and these entries are shown at the top of my ng-repeat feed. These should go to the bottom of the feed as they don't have a rating?

So an example of how i'd like this it to look is:

<ng-repeat orderBy:'-rating'>
  <place rating="5"/>
  <place rating="4.2"/>
  <place rating="2.8"/>
  <place rating="null"/>
  <place rating="null"/>
</ng-repeat>

What's the best way of going about this?

Dayle Salmon
  • 271
  • 2
  • 11
  • Check out this answer http://stackoverflow.com/questions/18604374/angularjs-orderby-with-empty-field/30028814 – DrinkBird Apr 22 '16 at 13:39

1 Answers1

10

To sort with null or undefined value using orderBy filter. use [] notation orderBy:[ '!rating', '-rating', ].

That will show null or undefined value at the bottom.

like:

 <li ng-repeat="option in options | orderBy:[ '!rating', '-rating', ]">{{option.name}}</li>
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
  • Thanks, this worked a treat. Wasn't aware that you could use arrays in the orderBy filter. I'm glad I didn't have to waste time to write up a custom filter. – Dayle Salmon Apr 26 '16 at 09:34
  • Well it's working on page load setting it to the scoped variable. But it doesn't seem to work in my select box. My code is like so: View: Controller: vm.order = ['!rating','-rating']; – Dayle Salmon Apr 26 '16 at 10:16
  • could you clarify more what do you want by update your answer ? – Shaishab Roy Apr 26 '16 at 18:01
  • So when a user clicks on the option sort by: 'High to Low' it should re-filter the array to [!rating, -rating]. But this value doesn't seem to work in a select box. – Dayle Salmon May 26 '16 at 21:08
  • It seems to also show 0 (zero) at the bottom. Any way to not include these at the bottom? – Jeremy Oct 03 '16 at 03:12
  • for your requirement you may need to create custom filter :)@Jeremy – Shaishab Roy Oct 03 '16 at 06:07
  • solution worked for me, you can also add double exclamations to switch the order of the null or undefined: orderBy: ['!!rating', '-rating'] Needed this and couldn't find it here – Luigi Cordoba Granera Jan 16 '19 at 21:06