Click the table headers to modify the sort order.
Name |
Country |
Jani |
Norway |
Carl |
Sweden |
Margareth |
England |
Hege |
Norway |
Joe |
Denmark |
Gustav |
Sweden |
Birgit |
Denmark |
Mary |
England |
Kai |
Norway |
By including the ng-click directive on the table headers, we can execute a function that alters the sorting order of the array.
<div ng-app=”myApp” ng-controller=”namesCtrl”> <table border=”1″ width=”100%”> <tr> <th ng-click=”orderByMe(‘name’)”>Name</th> <th ng-click=”orderByMe(‘country’)”>Country</th> </tr> <tr ng-repeat=”x in names | orderBy:myOrderBy”> <td>{{x.name}}</td> <td>{{x.country}}</td> </tr> </table> </div> <script> angular.module(‘myApp’, []).controller(‘namesCtrl’, function($scope) { $scope.names = [ {name:‘Jani’,country:‘Norway’}, {name:‘Carl’,country:‘Sweden’}, {name:‘Margareth’,country:‘England’}, {name:‘Hege’,country:‘Norway’}, {name:‘Joe’,country:‘Denmark’}, {name:‘Gustav’,country:‘Sweden’}, {name:‘Birgit’,country:‘Denmark’}, {name:‘Mary’,country:‘England’}, {name:‘Kai’,country:‘Norway’} ]; $scope.orderByMe = function(x) { $scope.myOrderBy = x; } }); </script> |
You can create custom filters by registering a new filter factory function with your module.
Create a custom filter named “myFormat.”
<ul ng-app=”myApp” ng-controller=”namesCtrl”>
<li ng-repeat=”x in names”> {{x | myFormat}} </li> </ul> <script> var app = angular.module(‘myApp’, []);
app.filter(‘myFormat‘, function() { return function(x) { var i, c, txt = “”; for (i = 0; i < x.length; i++) { c = x[i]; if (i % 2 == 0) { c = c.toUpperCase(); } txt += c; } return txt; }; }); app.controller(‘namesCtrl’, function($scope) { $scope.names = [‘Jani’, ‘Carl’, ‘Margareth’, ‘Hege’, ‘Joe’, ‘Gustav’, ‘Birgit’, ‘Mary’, ‘Kai’]; }); </script>
|
The myFormat filter will convert every other character to uppercase.