Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Sorting with null objects

I need to take records with null values on top , when I'm sorting by ASC

<tr ng-repeat="footballer in footballers=(footballers | orderBy:predicate)">
predicate : ['team.name','id]

Some footballers have no team, so team object == null and team.name==null, and I need to have them on the top

I wanted to rewrite sort function, but I need to save predicate

like image 579
rom16rus Avatar asked Dec 19 '22 11:12

rom16rus


1 Answers

You can use something like this in your controller:

$scope.nullsToTop = function(obj) {
  return (angular.isDefined(obj.team) ? 0 : -1);
};

And on the HTML:

<tr ng-repeat="footballer in footballers | orderBy:[nullsToTop].concat(predicate)">

This way you can maintain your predicate separately. Just concat the nullsToTop function in the orderBy expression to run it first.

Plunker

like image 172
bmleite Avatar answered Dec 30 '22 08:12

bmleite