title: AngularJS sort dynamic table
body: <p>I have a table that is generated dynamically using Angular 1.6. The data comes from a web API in JSON format. Here is a sample of the data.</p>
  
  <pre><code>{
    "CallData": [
      {
        "TableHeaders": [
          {
            "id": "0",
            "text": "Time"
          },
          {
            "id": "1",
            "text": "January"
          },
          {
            "id": "2",
            "text": "February"
          }
        ],
        "TableRows": [
          {
            "id": "0",
            "cells": [
              {
                "id": "0",
                "text": "7:00"
              },
              {
                "id": "1",
                "text": "0"
              },
              {
                "id": "2",
                "text": "0"
              }
            ]
          },
          {
            "id": "1",
            "cells": [
              {
                "id": "0",
                "text": "8:00"
              },
              {
                "id": "1",
                "text": "18"
              },
              {
                "id": "2",
                "text": "83"
              }
            ]
          }
        ]
      }
    ]
  }
  </code></pre>
  
  <p>Here is my HTML that is generating the table:</p>
  
  <pre><code>&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th ng-repeat="header in data.TableHeaders"&gt;
              {{header.text}}
          &lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr ng-repeat="row in data.TableRows"&gt;
          &lt;td ng-repeat="cell in row.cells"&gt;
              {{cell.text}}
          &lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>I want to be able to sort my data when I click on the headers. However, I have so far tried to set a sort variable to the <code>id</code> of the headers, using <code>ng-click</code>, and I can see that it updates the variable, but it doesn't sort the data. This was using <code>ng-repeat="row in data.TableRows | orderBy: sortVar"</code></p>
  
  <p>My sorting code:</p>
  
  <pre><code>// Initialise variable
  $scope.sortVar = '0';
  
  &lt;!-- HTML snippet --&gt;
  &lt;th ng-repeat="header in data.TableHeaders" ng-click="updateSort(header.id)"&gt;&lt;/tr&gt;
  
  // function
  $scope.updateSort = function(id) {
      $scope.sortVar = id;
  }
  </code></pre>
  
  <p>Is there any way at all to be able to sort my dynamic tables? Am I going to need to add another value to my JSON data in order to do this? </p>
  
  <p>I'm relatively new to angular, so not 100% sure how to achieve this.</p>
  
  <p>If anything is unclear, let me know and I'll try to explain it a bit better.</p>
  
  <p>Cheers</p>