mjt mjt - 3 months ago 12
AngularJS Question

angularjs sort orderby on array

I have data like

{ column : [a,b,c], data : [["a",1,2],["b",4,5],["c",3,2]]}


table structure

<thead>
<tr>
<th ng-repeat="n in column" ng-click="click($index)">n</th>
</tr>
</thead>
<tr ng-repeat="i in data | orderBy:sortType:sortReverse ">
<td ng-repeat="j in i">i</td>
</tr>


how to make a sort logic here??

Answer

You can try order by with a custom function. An example below. Hope this helps.

angular.module("app", []);
angular.module("app").controller("Test", function($scope) {
  $scope.sortReverse = false;
  $scope.column = ['a', 'b', 'c'];
  $scope.data = [
    ["a", "1", "2"],
    ["b", "4", "5"],
    ["c", "3", "2"]
  ];

  $scope.sort = function(index) {
    $scope.sortColumnIndex = index;
    $scope.sortReverse = !$scope.sortReverse;
  };

  $scope.sortByIndex = function(item) {
    return item[$scope.sortColumnIndex];
  };

});
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body>
  <div ng-controller="Test">
    <table>
      <thead>
        <tr>
          <th ng-repeat="n in column" ng-click="sort($index)">{{n}}</th>
        </tr>
      </thead>
      <tr ng-repeat="i in data | orderBy:sortByIndex:sortReverse">
        <td ng-repeat="j in i">{{j}}</td>
      </tr>
    </table>
  </div>
</body>

</html>

Comments