简体   繁体   中英

AngularJS orderBy via function

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM