1

What is the difference between the following two snippets when trying to orderBy via a function:

<li ng-repeat="str in arrOfStrings | orderBy: 'toString()'> {{str}} </li>

and

<li ng-repeat="person in people | orderBy: getSortKey()> {{person.firstName}} {{person.lastName}}: {{person.email}} </li>
$scope.getSortKey = function() {
    return "lastName";
}

Also I wonder how the toString() method is helpful in sorting array of strings. See How to make orderby filter work on array of strings?

1 Answer 1

4

In first case you say to use property or method of elements in array

In second case you say to use method or property from global (actually current) scope, that should return what will be applied to array elements, ie it will be executed first, and that is why your second example can be simplified to

 <li ng-repeat="person in people | orderBy: 'lastName'>

Example of typical use of second case would be sorting in table. You can have something like this:

 <table>
   <tr><td ng-click='sortColumn="a"'>a<td><td ng-click='sortColumn="b"'></td>
   </tr>
   <tr ng-repeat="e in elements | orderBy: sortColumn"><td>{{ a }}</td><td>{{ b }}</td></tr>
 </table>

To be more precise - orderBy accept either string as parameter or function that returns a string. String should be name of property or method call on array element.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation. Correct me if I am wrong: In the first case, the orderBy: 'toString()' will first convert the array into comma separated string and then sort them. Right?
@AnupVasudeva no. in first case array will be sorted by str.toString() values, ie .toString() call on each array element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.