Search code examples
angularjsfilterangularjs-orderby

Custom filter in Angular with undefined values


I have an array of objects in Angular that I am trying to sort a very specific way and I can't figure it out.

Here's sample Javascript:

var app = angular.module('app', []);

function Ctrl($scope) {
  $scope.divisions = [      
      {'group':'d','sub':1}, 
      {'group':'a'}, 
      {'group':'z','sub':2},
      {'group':'g','sub':20},
      {'group':'g'},
      {'group':'r','sub':11}];
}

Here's sample HTML:

<div class="test" ng-controller="Ctrl">
  <div ng-repeat="division in divisions | orderBy:['sub','group']">{{division.group}}-{{division.sub}}</div>
<div>

Here's the fiddle: https://jsfiddle.net/r4nsyp2v/1/

And instead of it displaying like:

d-1
z-2
r-11
g-20
a-
g-

I want it to display like:

g-20
r-11
z-2
d-1
a-
g-

So I would want to display the 'sub' key from largest to smallest if it exists, with the undefined 'sub' keys after. And display the objects with undefined 'sub' keys alphabetically by group.

I haven't found the trick yet....any ideas?


Solution

  • You could create your custom order like this:

    $scope.order = function(division) {
      return -(division.sub || 0);
    }
    

    And in the HTML

    <div ng-repeat="division in divisions | orderBy:order">
    

    See example https://jsfiddle.net/r4nsyp2v/2/