如果我知道页面数,如何在AngularJS中创建页面项?

时间:2018-07-13 13:50:28

标签: javascript jquery html angularjs

我正在开发一个小型应用程序,该应用程序在 HTML5表中显示“用户” JSON。它使用Bootstrap 3和AngularJS。我想对这张桌子进行分页。

我没有使用ng-repeat遍历的数组。我有 number 页数

使用jQuery,我会这样做:

var pageMax = 10;

var paginationItems = [];
for(var i=0; i<pageMax; i++){
    var paginationItem = '<li><a href="#">' + (i + 1) + '</a></li>';
    paginationItems.push(paginationItem);
}
var paginationSum = paginationItems.reduce((a, b) => a + b, '');
$('.pagination').html(paginationSum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="text-center">
  <ul class="pagination"></ul>
</div>

与AngularJS中的for循环等效吗?

2 个答案:

答案 0 :(得分:2)

按角度,您将执行以下操作:

angular.module('app', [])
  .controller('Controller', function($scope) {
   $scope.pageMax = 10;
   
   $scope.pages = new Array($scope.pageMax);
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<body ng-app="app">
  <div ng-controller="Controller">
    <div class="text-center">
    <h3>Initialized in template:</h3>
      <ul class="pagination">
        <li ng-repeat="n in [].constructor(pageMax) track by $index">
          <a href="#">{{$index+1}}</a>
        </li>
      </ul>
      
      <h3>Initialized in controller:</h3>
      <ul class="pagination">
        <li ng-repeat="n in pages track by $index">
          <a href="#">{{$index+1}}</a>
        </li>
      </ul>
    </div>
  </div>
</body>

答案 1 :(得分:2)

您可以使用ng-repeat来做到这一点。

请注意,当您要渲染HTML时,必须对AngularJS使用$sce.trustAsHtml才能实际渲染HTML。然后,您可以在ng-bind-html中使用HTML

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

var DummyController = function($scope, $sce) {
  var pageMax = 10;

  $scope.paginationItems = [];

  for (var i = 0; i < pageMax; i++) {
    var item = $sce.trustAsHtml('<a href="#">' + (i + 1) + '</a>');
    $scope.paginationItems.push(item);
  }
}

app.controller(DummyController, ["$scope, $sce", "DummyController"]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div ng-app="Dummy">
  <div class="text-center" ng-controller="DummyController">
    <ul class="pagination">
      <li ng-bind-html="item" ng-repeat='item in paginationItems'></li>
    </ul>
  </div>
</div>