Monday, August 25, 2014

AngularJS sortable table

CodePen - Pen



<section ng-app="app" ng-controller="MainCtrl">

  <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>

  <table class="table table-bordered">

    <thead>

      <tr>

        <th>

          <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">

          First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>

          </a>

        </th>

        <th>

          <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">

            Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>

          </a>

        </th>

        <th>

          <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">

          Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>

          </a>

        </th>

      </tr>

    </thead>

    <tbody>

      <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">

        <td>{{emp.firstName}}</td>

        <td>{{emp.lastName}}</td>

        <td>{{emp.age}}</td>

      </tr>

    </tbody>

  </table>

</section>







var app = angular.module('app', []);



app.controller('MainCtrl', function($scope) {

  $scope.orderByField = 'firstName';

  $scope.reverseSort = false;

 

  $scope.data = {

    employees: [{

      firstName: 'John',

      lastName: 'Doe',

      age: 30

    },{

      firstName: 'Frank',

      lastName: 'Burns',

      age: 54

    },{

      firstName: 'Sue',

      lastName: 'Banter',

      age: 21

    }]

  };

});

No comments: