You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用UI Bootstrap与AngularJS 1 Resource实现JSON对象分页?

实现JSON对象的Bootstrap分页(uib-pagination)

我来帮你搞定这个分页功能,结合你现有的AngularJS应用,一步步来实现:

1. 补全Home控制器的分页逻辑

首先在你的HomeCtrl里添加分页所需的变量和处理逻辑,假设你已经有了要分页的JSON数据集(这里用originalData示例,你替换成自己的实际数据即可):

.controller('HomeCtrl', ['$scope', function($scope) {
  // 示例JSON数据,替换成你的实际业务数据
  $scope.originalData = [
    {id: 1, name: "商品A", price: 99},
    {id: 2, name: "商品B", price: 199},
    {id: 3, name: "商品C", price: 299},
    // ... 更多数据项
  ];

  // 分页核心参数配置
  $scope.currentPage = 1; // 默认显示第一页
  $scope.itemsPerPage = 10; // 每页展示10条数据
  $scope.totalItems = $scope.originalData.length; // 总数据条数

  // 监听页码或每页条数变化,实时更新展示数据
  $scope.$watchGroup(['currentPage', 'itemsPerPage'], function() {
    var startPos = ($scope.currentPage - 1) * $scope.itemsPerPage;
    var endPos = startPos + $scope.itemsPerPage;
    $scope.displayData = $scope.originalData.slice(startPos, endPos);
  });
}])

2. 在Home模板中添加Bootstrap分页组件

在home.html里先展示分页后的数据,再嵌入uib-pagination组件,确保样式和功能都符合Bootstrap规范:

<!-- 分页数据展示区 -->
<div class="container mt-4">
  <div class="row row-cols-1 row-cols-md-3 g-4" ng-repeat="item in displayData">
    <div class="col">
      <div class="card h-100">
        <div class="card-body">
          <h5 class="card-title">{{item.name}}</h5>
          <p class="card-text">ID: {{item.id}}</p>
          <p class="card-text text-primary">¥{{item.price}}</p>
        </div>
      </div>
    </div>
  </div>

  <!-- uib-pagination分页组件 -->
  <div class="d-flex justify-content-center mt-4">
    <uib-pagination 
      total-items="totalItems"
      ng-model="currentPage"
      items-per-page="itemsPerPage"
      max-size="5" <!-- 分页栏最多显示5个页码 -->
      boundary-links="true" <!-- 显示首页/末页跳转按钮 -->
      first-text="«"
      last-text="»"
      previous-text="‹"
      next-text="›"
      class="pagination"
    ></uib-pagination>
  </div>
</div>

3. 关键细节说明

  • 数据截取逻辑:通过JavaScript的slice()方法从原始数据中截取当前页需要展示的片段,配合$watchGroup监听页码或每页条数的变化,实现数据的实时更新。
  • uib-pagination参数解析:
    • total-items:绑定总数据条数,用于自动计算总页数
    • ng-model:绑定当前选中的页码
    • items-per-page:控制每页展示的数据量
    • max-size:限制分页栏中显示的页码数量,避免页码过多导致排版混乱
    • boundary-links:开启后会显示首页和末页的快速跳转按钮
  • Bootstrap样式适配:用d-flex justify-content-center让分页组件居中,card和row-cols布局美化数据展示,确保整体风格和Bootstrap统一。

4. 注意事项

  • 确保你的项目已经正确引入Bootstrap的CSS文件,否则分页组件的样式会显示异常。
  • 如果你的数据是通过异步请求获取的(比如从后端API拉取),记得在数据加载完成后再更新totalItems并触发数据截取逻辑。

内容的提问来源于stack exchange,提问作者Neo Sono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:03:13