AngularJS实现分页显示数据库信息

前端技术 2023/09/06 JavaScript

接着第一篇《》AngularJS内建服务$location及其功能详解》,进行学习

Section 2:实现分页显示效果

那么再隐身一下,通过location的setter方法设置当前的url信息。在这里为了能够让演示看到更好的效果,在这个比较完整的实例中,我引入了angularJS的多路由技术、嵌套的控制器之间传递数据、scope的继承、 http通信、内链接传递变量等。

首先建立一个首页模板

<!DOCTYPE html>
<html ng-app=\"turnPageApp\">
<head lang=\"en\">
  <meta charset=\"UTF-8\">
  <title></title>
  <script src=\"lib/angular.js\"></script>
  <script src=\"lib/angular-route.min.js\"></script>
  <style type=\"text/css\">
    .turnPageButtonArea {
      background-color: #f07a13;
      width: 500px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      margin: 10px auto;
      padding: 20px;
    }

    button {
      margin-right: 20px;
      width: 100px;
      height: 30px;
      font-size: 15px;
    }

    .pageNum {
      width: 50px;
      height: 23px;
      text-align: center;
    }

    body {
      font-family: 微软雅黑;
    }

    h1 {
      text-align: center;
    }

    .totalPages {
      color: #ffffff
    }
  </style>
</head>
<body ng-controller=\"indexController\">
<h1>AngularJS TurnPage By $location Service</h1>

<div ng-view></div>
<div class=\"turnPageButtonArea\">
  <button ng-click=\"previous()\">Previous</button>
  <button ng-click=\"next()\">Next</button>
  <input type=\"number\" ng-model=\"currentPage\" class=\"pageNum\">
  <button ng-click=\"goToPage()\">Go</button>
  <span class=\"totalPages\">共 {{allPage}} 页</span>
</div>
</body>
</html>

通过一些简单的CSS样式将页面的布局修饰了一下。

然后在首页的元素里设置了一些ngApp和controller。

在属性为ngView的div元素中,将嵌入其他HTML的模板。

紧接着下方,我摆放了三个按钮,其中前两个是上一页和下一页的翻页按钮;一个输入框可供用户输入他想跳转到的页码,旁边的按钮作为页码的提交按钮,点击后页面立即翻页。

这三个按钮里面都有一个ngClick属性,表示当用户点击按钮后,便会执行对应的函数。

在讲解angularJS的js代码前,先截图看看文件的目录结构。

上面的index.html是之前两个例子的,可以不去理会。

为了简单期间,我把script脚本都放在了turnPage.html文件的下方了。下面就是全这个文件的完整代码:

turnPage.html

<!DOCTYPE html>
<html ng-app=\"turnPageApp\">
<head lang=\"en\">
  <meta charset=\"UTF-8\">
  <title></title>
  <script src=\"lib/angular.js\"></script>
  <script src=\"lib/angular-route.min.js\"></script>
  <style type=\"text/css\">
    .turnPageButtonArea {
      background-color: #f07a13;
      width: 500px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      margin: 10px auto;
      padding: 20px;
    }

    button {
      margin-right: 20px;
      width: 100px;
      height: 30px;
      font-size: 15px;
    }

    .pageNum {
      width: 50px;
      height: 23px;
      text-align: center;
    }

    body {
      font-family: 微软雅黑;
    }

    h1 {
      text-align: center;
    }

    .totalPages {
      color: #ffffff
    }
  </style>
</head>
<body ng-controller=\"indexController\">
<h1>AngularJS TurnPage By $location Service</h1>

<div ng-view></div>
<div class=\"turnPageButtonArea\">
  <button ng-click=\"previous()\">Previous</button>
  <button ng-click=\"next()\">Next</button>
  <input type=\"number\" ng-model=\"currentPage\" class=\"pageNum\">
  <button ng-click=\"goToPage()\">Go</button>
  <span class=\"totalPages\">共 {{allPage}} 页</span>
</div>
<script>
  //实例化用户自己的ngApp对象。这里因为用到了路由机制,所以在依赖注入中写入ngRoute这个模块
  var turnPageApp = angular.module(\'turnPageApp\', [\'ngRoute\']);
  /*
   设置对于不同的url,启用不同的模板和控制器。
   本例由于只用到了一个模板,所以遇到的路由的情况就只有一种,即 “/id”
   */
  turnPageApp.config([\'$routeProvider\', function ($routeProvider) {
    $routeProvider
        .when(\'/:id\', { //这里的id其实表示的是翻页中的页码
          templateUrl: \'view/student.html\',
          controller: \'StudentController\'
        })
        .otherwise({redirectTo: \'/1\'});//如果没法匹配到url时,直接跳转会第一页
  }]);
  //注册父控制器indexController,这里由于需要将模板里的子控制器的值传递给父控制器,所以需要这个根域$rootScope来帮忙,在返回函数里需要传入这个根域对象。
  //而且,本例是基于对url的操作来实现翻页,所以这个内建的$location服务是一定要传入的
  turnPageApp.controller(\'indexController\', function ($rootScope, $scope, $location) {
    //给父scope定义函数
    $scope.previous = function () {
      //从浏览器的地址栏获取路径,即turnPage.html#/1中井号后面的内容:“ /1 ”
      //然后通过JavaScript的silce函数取出斜杠后面的字符,并转换成数字。
      //加 1 还是减 1 要看是在定义的是哪个按钮的功能函数了
      var pageNum = parseInt($location.path().slice(1)) - 1;
      //页码是有限的,需要做一些判断
      if (pageNum < 1) {
        alert(\'This is the first page\');
      } else {
        //如果现在没有处在第一页,则path属性减去1,即向前翻一页。这个翻页的效果就是通过设置url中的path来实现
        $location.path(pageNum);
      }
    };
    //和上面的previous()函数类似
    $scope.next = function () {
      var pageNum = parseInt($location.path().slice(1)) + 1;
      if (pageNum > $rootScope.allPage) {
        alert(\'This is the last page\');
      } else {
        $location.path(pageNum);
      }
    };
    //这是一个直接跳转到那个页码的函数,在判断的地方稍微繁琐些
    $scope.goToPage = function () {
      //从input输入框绑定的currentPage变量中获取用户输入的值
      var pageNum = $scope.currentPage;
      //为了程序的严密和可用性,需要先判断输入是否为空
      if (pageNum == null || pageNum == undefined || pageNum == \"\") {
        alert(\"try to input a page number\");
        //如果不是空,再判断用户输入的页码是否超出了页码的范围
        //这里出现了$rootScope这个根域及其属性allPage,该属性的值是页码的总数
      } else if (!(pageNum >= 1 && pageNum <= $rootScope.allPage)) {
        alert(\"The page number is beyond the scope of the number of the students\")
      } else {
        //如果都没问题了,则修改URL,此时angularJS会捕捉地址栏的变化,然后跳转,细节将在下面讲解。
        $location.path(pageNum);
      }
    };
  });
  //这里实在注册嵌入到首页的模板页的控制器。
  //由于子域和父域的通信需要借助根域,所以在依赖中传入$rootScope对象
  //$scope是模板自己的作用域,它继承了父控制器indexController生成的作用域
  //在模板中需要与服务端的文件进行交互,所以需要引入内建的$http服务。为了控制实例的复杂度,我直接写了一个json文件,做了一些假数据。
  //这里$routeParams是一个对象,这个对象里有一个属性,就是我们之前在config()函数里看到的那个id(/:id),这个id是个变量,地址栏里的path是几,这个id就是几。id的值需要通过$routeParams这个对象来取得。
  turnPageApp.controller(\'StudentController\', [\'$rootScope\', \'$scope\', \'$http\', \'$routeParams\', function ($rootScope, $scope, $http, $routeParams) {
    //$http的get方法与远程的一个文件发出请求,如果成功,则执行一个回调函数,函数的参数就是从远端文件里拿到的数据,这个数据可以是个数组,也可以是个对象。
    //那么我们这次拿到的是一个json数组,数组的元素是一个个的对象。
    $http.get(\'data/students.json\').success(function (data) {
      //把数组里的一个元素取出来,赋给模板子作用域对象的属性上。由于json数组的id是从1开始写的,而返回的数据是个数组,下标从0开始,所以要减去1
      $scope.student = data[$routeParams.id - 1];
      //这里顺便把这个数组的元素个数取出来,每个元素就代表以页。那么元素总个数就代表共有多少页。
      //注意要传递给最高级别的根域对象,因为子域能覆写父域的同名属性;子域如果没有直接赋值,那么子域的同名属性将继承父域同名属性的值;
      /*我们在回到本文件代码上面的“共 {{allPage}} 页”处,这个就是根域$rootScope的属性。而且在父控制器中并没有特别的赋值。而这个span元素恰好就在父控制器的作用域内,那么这个元素里的allPage属性就会继承父作用域的同名属性allPage的值,也就间接的显示出了总页数。
      */
      $rootScope.allPage = data.length;
    });
  }]);
</script>
</body>
</html>

view/student.html

<table cellspacing=\"0\">
  <tr>
    <td class=\"title\">ID</td>
    <td>{{student.id}}</td>
  </tr>
  <tr>
    <td class=\"title\">Name</td>
    <td>{{student.name}}</td>
  </tr>
  <tr>
    <td class=\"title\">Sex</td>
    <td>{{student.sex}}</td>
  </tr>
  <tr>
    <td class=\"title\">Age</td>
    <td>{{student.age}}</td>
  </tr>
  <tr>
    <td class=\"title\">Courses</td>
    <td>
      <ul>
        <li ng-repeat=\"course in student.courses\">{{course}}</li>
      </ul>
    </td>
  </tr>
</table>
<style type=\"text/css\">
  table {
    border: solid 1px #000000;
    margin: 0px auto;
  }

  td {
    padding: 10px 10px 10px 20px;
    margin: 0px;
    border: solid 1px #000000;
  }

  tr {
    margin: 0px;
    padding: 0px;

  }

  .title {
    background-color: #207ef0;
    text-align: center;
    color: #ffffff;
  }

  ul {
    list-style: none;
    margin: 0px;
    padding: 0px;
  }

  li {
    float: left;
    margin: 10px;
  }
</style>

data/students.json

[
 {
  \"id\": 1,
  \"name\": \"Frank Li\",
  \"sex\": \"male\",
  \"age\": \"30\",
  \"courses\": [
   \"HTML\",
   \"CSS\",
   \"Javascript\",
   \"Java\",
   \"PHP\",
   \"MySQL\",
   \"Ubuntu\",
   \"MongoDB\",
   \"NodeJS\",
   \"AngularJS\",
   \"Photoshop\",
   \"LESS\",
   \"Bootstrap\"
  ]
 },
 {
  \"id\": 2,
  \"name\": \"Cherry\",
  \"sex\": \"female\",
  \"age\": \"27\",
  \"courses\": [
   \"Anderson\'s Fairy Tales\",
   \"Pride and Prejudice\",
   \"Vanity Fair\",
   \"Oliver Twist\"
  ]
 },
 {
  \"id\": 3,
  \"name\": \"John Liu\",
  \"sex\": \"male\",
  \"age\": \"29\",
  \"courses\": [
   \"iology and medical science\",
   \"pplied biology\",
   \"medicine\",
   \"cell biology\"
  ]
 },
 {
  \"id\": 4,
  \"name\": \"Lucy Mu\",
  \"sex\": \"female\",
  \"age\": \"22\",
  \"courses\": [
   \"Introduction to ART \",
   \"sketch\",
   \"Composition\",
   \"sculpture\"
  ]
 }
]

这是刚开始的样子,地址栏中默认的path是/1,所以直接显示了第一个学生的信息。页码总数也能获得。

点击了Previous按钮后的效果。不能再往前翻页了

处于第4页时,点击Next按钮时的效果。不能再往后翻页了。

在页码范围内翻页是没有问题的!

鉴于篇幅,我就不演示输入的页码超出范围的情况了。上面的截图是输入正确范围的页码,点击Go按钮的效果。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持phpstudy。

本文地址:https://www.stayed.cn/item/16865

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。