妙用Angularjs实现表格按指定列排序

晨曦的阳光淌进窗户,给你送出我的祝福,打开手机查看,温馨,一点点爬上你的笑脸,你是快乐的,我就是幸福的,早安!

使用AngularJS的过滤器,可以很容易的实现在表格中,点击某一列标题进行排序,实现过程如下:

html代码:

<table class="table table-border" ng-app="myapp" ng-controller="orderByCtrl">
  <thead>
    <tr>
      <th>inx</th>
      <th ng-click="col='name';desc=!desc">name</th>
      <!-- 当点击列标题时,执行click事件,将排序条件反转,即,如果原来是升序则将按降序,降序亦如此 -->
      <th ng-click="col='gender';desc=!desc">gender</th>
      <th ng-click="col='age';desc=!desc">age</th>
      <th ng-click="col='score';desc=!desc">score</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="d in data|orderBy:col:desc">
      <td ng-bind="$index+1"></td>
      <td ng-bind="d.name"></td>
      <td ng-bind="d.gender"></td>
      <td ng-bind="d.age"></td>
      <td ng-bind="d.score"></td>
    </tr>
  </tbody>
</table>

js代码:

var app = angular.module('myapp', []);
app.controller('orderByCtrl', function($scope) {
  $scope.col = 'name';//默认按name列排序
  $scope.desc = 0;//默认排序条件升序
  $scope.data = [{
    name: 'name 1',
    gender: 'male',
    age: 26,
    score: 70
  }, {
    name: 'name 2',
    gender: 'female',
    age: 24,
    score: 84
  }, {
    name: 'name 3',
    gender: 'male',
    age: 20,
    score: 76
  }, {
    name: 'name 4',
    gender: 'female',
    age: 22,
    score: 64
  }];
})

让运行界面好看些,使用了bootstrap.min.css样式库。为了交互性考虑,在表头增加了手指样式

th {
  cursor: pointer;
}

以上所述是小编给大家介绍的妙用Angularjs实现表格按指定列排序,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

本文妙用Angularjs实现表格按指定列排序到此结束。这一生中,我们固执地以自己喜欢的方式存在着,并渴望与自己同行的人,也能按照这种方式来演绎生活的节奏。于是,为了生计、爱情和梦想,我们在无数次的摩擦与碰撞中,慢慢地改变着并湮没了原来的自己。来到这个世界上,我们谁都没有错,就是因为固守或者改变得太多,我们错过了很多烟花般的美丽。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
AngularJS tab栏实现和mvc小案例实例详解

基于AngularJS拖拽插件ngDraggable.js实现拖拽排序功能

AngularJS实现的自定义过滤器简单示例

ionic使用angularjs表单验证(模板验证)

用WebStorm进行Angularjs 2开发(环境篇:Windows 10,Angular-cli方式)