AngularJS sorting rows by table header

后端 未结 9 1910
旧巷少年郎
旧巷少年郎 2020-12-04 07:08

I have four table headers:

$scope.headers = [\"Header1\", \"Header2\", \"Header3\", \"Header4\"];

And I want to be able to sort my table by

9条回答
  •  独厮守ぢ
    2020-12-04 07:46

    Another way to do this in AngularJS is to use a Grid.

    The advantage with grids is that the row sorting behavior you are looking for is included by default.

    The functionality is well encapsulated. You don't need to add ng-click attributes, or use scope variables to maintain state:

        
            

    You just add the grid options to your controller:

      $scope.gridOptions = {
        data: 'myData.employees',
        columnDefs: [{
          field: 'firstName',
          displayName: 'First Name'
        }, {
          field: 'lastName',
          displayName: 'Last Name'
        }, {
          field: 'age',
          displayName: 'Age'
        }]
      };
    

    Full working snippet attached:

    var app = angular.module('myApp', ['ngGrid', 'ngAnimate']);
    app.controller('MyCtrl', function($scope) {
    
      $scope.myData = {
        employees: [{
          firstName: 'John',
          lastName: 'Doe',
          age: 30
        }, {
          firstName: 'Frank',
          lastName: 'Burns',
          age: 54
        }, {
          firstName: 'Sue',
          lastName: 'Banter',
          age: 21
        }]
      };
    
      $scope.gridOptions = {
        data: 'myData.employees',
        columnDefs: [{
          field: 'firstName',
          displayName: 'First Name'
        }, {
          field: 'lastName',
          displayName: 'Last Name'
        }, {
          field: 'age',
          displayName: 'Age'
        }]
      };
    });
    /*style.css*/
    .gridStyle {
        border: 1px solid rgb(212,212,212);
        width: 400px;
        height: 200px
    }
    
    
        
            
            Custom Plunker
            
            
            
            
            
            
            
        
        
            

提交回复
热议问题