angularjsangularjs-ng-repeatangularjs-orderby

orderBy in ngRepeat using another variable property


Is it possible to sort items from one array based on another variable by only using orderBy and not adding a count property to the items in the array?

Lets say i have an array and a map in the controller:

$scope.x = [{no:1,name:"a"},
    {no:2,name:"b"},
    {no:3,name:"c"}];

$scope.y = { 1: [1],
    2: [1,2,3],
    3: [1,2] };

and the html will look like this:

<div ng-repeat="i in x | orderBy: y[i.no].length">
  {{i.no}}
  {{ y[i.no] }}
  {{ y[i.no].length }}
</div>

output:

1 [1] 1
2 [1,2,3] 3
3 [1,2] 2

but it should be:

1 [1] 1
3 [1,2] 2
2 [1,2,3] 3

Solution

  • You could use a predicate function, to specify your condition.

    Try this:

    <div ng-repeat="i in x | orderBy: findOrder">
        {{i.no}}
        {{ y[i.no] }}
        {{ y[i.no].length }}
    </div>
    

    And:

    $scope.findOrder = function(elem){
          console.log(elem.no);
          return $scope.y[elem.no].length;
     }
    

    A working fiddle.