angular.Array.orderBy

Description

Orders a specified array by the expression predicate.

Note: this function is used to augment the Array type in Angular expressions. See angular.Array for more informaton about Angular arrays.

Usage

angular.Array.orderBy(array, expression[, reverse]);

Parameters

Returns

{Array}

Sorted copy of the source array.

Example

  <script>
    function Ctrl() {
      this.friends =
          [{name:'John', phone:'555-1212', age:10},
           {name:'Mary', phone:'555-9876', age:19},
           {name:'Mike', phone:'555-4321', age:21},
           {name:'Adam', phone:'555-5678', age:35},
           {name:'Julie', phone:'555-8765', age:29}]
      this.predicate = '-age';
    }
  </script>
  <div ng:controller="Ctrl">
    <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
    <hr/>
    [ <a href="" ng:click="predicate=''">unsorted</a> ]
    <table class="friend">
      <tr>
        <th><a href="" ng:click="predicate = 'name'; reverse=false">Name</a>
            (<a href ng:click="predicate = '-name'; reverse=false">^</a>)</th>
        <th><a href="" ng:click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
        <th><a href="" ng:click="predicate = 'age'; reverse=!reverse">Age</a></th>
      <tr>
      <tr ng:repeat="friend in friends.$orderBy(predicate, reverse)">
        <td>{{friend.name}}</td>
        <td>{{friend.phone}}</td>
        <td>{{friend.age}}</td>
      <tr>
    </table>
  </div>
  it('should be reverse ordered by aged', function() {
    expect(binding('predicate')).toBe('Sorting predicate = -age; reverse = ');
    expect(repeater('table.friend', 'friend in friends').column('friend.age')).
      toEqual(['35', '29', '21', '19', '10']);
    expect(repeater('table.friend', 'friend in friends').column('friend.name')).
      toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
  });

  it('should reorder the table when user selects different predicate', function() {
    element('.doc-example-live a:contains("Name")').click();
    expect(repeater('table.friend', 'friend in friends').column('friend.name')).
      toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
    expect(repeater('table.friend', 'friend in friends').column('friend.age')).
      toEqual(['35', '10', '29', '19', '21']);

    element('.doc-example-live a:contains("Phone")').click();
    expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
      toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
    expect(repeater('table.friend', 'friend in friends').column('friend.name')).
      toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
  });