Подтвердить что ты не робот

Как сообщить ui-Bootstrap, какой контент нужно разбивать на страницы?

Я использую ui-Bootstrap, и я пытаюсь заставить постраничную работу работать, но, похоже, что-то не хватает. Я прочитал документацию и посмотрел на кучу плунжеров, чтобы попытаться выяснить, как они определяют, какой контент нужно разбивать на страницы, но мне не повезло.

Вот что я сделал http://plnkr.co/edit/5mfiAcOaGw8z8VinhIQo?p=preview

<section class="main" ng-controller="contentCtrl">
  <div ng-repeat="friend in friends">
    {{friend.name}}
  </div>
  <pagination total-items="totalItems" items-per-page="itemsPerPage" ng-model="currentPage" ng-change="pageChanged()"></pagination>

  <p>
    total Items: {{totalItems}}<br />
    Items per page: {{itemsPerPage}}<br />
    Current Page: {{currentPage}}
  </p>
</section>

Контроллер:

angular.module('plunker', ['ui.bootstrap'])
  .controller('contentCtrl', function ($scope) {

    $scope.friends = [
      {'name':'Jack'},
      {'name':'Tim'},
      {'name':'Stuart'},
      {'name':'Richard'},
      {'name':'Tom'},
      {'name':'Frank'},
      {'name':'Ted'},
      {'name':'Michael'},
      {'name':'Albert'},
      {'name':'Tobby'},
      {'name':'Mick'},
      {'name':'Nicholas'},
      {'name':'Jesse'},
      {'name':'Lex'},
      {'name':'Robbie'},
      {'name':'Jake'},
      {'name':'Levi'},
      {'name':'Edward'},
      {'name':'Neil'},
      {'name':'Hugh'},
      {'name':'Hugo'},
      {'name':'Yanick'},
      {'name':'Matt'},
      {'name':'Andrew'},
      {'name':'Charles'},
      {'name':'Oliver'},
      {'name':'Robin'},
      {'name':'Harry'},
      {'name':'James'},
      {'name':'Kelvin'},
      {'name':'David'},
      {'name':'Paul'}
    ];

    $scope.totalItems = 64;
    $scope.itemsPerPage = 10
    $scope.currentPage = 1;

    $scope.setPage = function (pageNo) {
      $scope.currentPage = pageNo;
    };

    $scope.pageChanged = function() {
      console.log('Page changed to: ' + $scope.currentPage);
    };

    $scope.maxSize = 5;
    $scope.bigTotalItems = 175;
    $scope.bigCurrentPage = 1;
  });
4b9b3361

Ответ 1

Я мог бы просто добавить следующие ссылки:

  • bootstrap-css
  • angular.js
  • angular -ui-самозагрузка

Ваше тело может выглядеть так:

<html ng-app="friends"> 
<head>
...
</head>
<body>
   <h4>Paginated Friends</h4>
   <section class="main" ng-controller="contentCtrl">
      <div ng-repeat="friend in filteredFriends">
         {{friend.name}}
      </div>
      <pagination total-items="totalItems" items-per-page="itemsPerPage" 
         ng-model="currentPage" ng-change="pageChanged()"></pagination>
      <p>
         Total items: {{totalItems}}<br />
         Items per page: {{itemsPerPage}}<br />
         Current Page: {{currentPage}}
      </p>
   </section>
</body>
</html>

Затем определите следующий контроллер:

var app = angular.module('plunker', ['ngResource', 'ui.bootstrap']);

app.factory('friendsFactory', function($resource) {
  return $resource('friends.json');
});

app.controller('contentCtrl', function ($scope, friendsFactory) {
  $scope.friends = friendsFactory.query();

  $scope.itemsPerPage = 10
  $scope.currentPage = 1;

  // $scope.maxSize = 5;
  // $scope.bigTotalItems = 175;
  // $scope.bigCurrentPage = 1;

  $scope.pageCount = function () {
    return Math.ceil($scope.friends.length / $scope.itemsPerPage);
  };

  $scope.friends.$promise.then(function () {
    $scope.totalItems = $scope.friends.length;
    $scope.$watch('currentPage + itemsPerPage', function() {
      var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
        end = begin + $scope.itemsPerPage;

      $scope.filteredFriends = $scope.friends.slice(begin, end);
    });
  });
});

Ответ 2

ui-bootstrap 0.10 не использует ng-модель для обновления текущей страницы.

используйте page="currentPage" для отображения текущей страницы.

используйте on-select-page="setPage(page)" для изменения текущей страницы.

Пример здесь:

http://plnkr.co/edit/UIWIeDSKIK4bG96eoJmt?p=preview

если вы хотите использовать ng-model. обновите версию ui-bootstrap до 0.11

Ответ 3

Вы можете использовать переменные, созданные в ng-repeat. Это работает. Я использую его, пока не изменю его.

ng-repeat="friend in friends.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage)) track by $index"

Однако я обнаружил, что лучшим решением этой проблемы является создание фильтра и его цепочка. Поместите это последним в цепочку, так как вы, вероятно, захотите использовать другие фильтры перед этим. Вот пример использования фильтра orderby. Разница в том, что вы можете затем упорядочить весь массив, а затем разбивать на страницы и показывать только ту часть, которую вы хотели бы показать.

function paginateFilter() {
  return function (friends, currentPage, itemsPerPage) {
    var filteredFlowers = flowers.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage))
    return filteredFriends;
  };
}

И вот html. Вам придется использовать фильтр с несколькими переменными.

ng-repeat="friend in main.friends |orderBy: 'name' | paginate: main.currentPage: main.itemsPerPage">

Где main - имя controllerAs.

Ответ 4

с использованием угловых компонентов 1.5 и Typescript

searchresults.controller.ts

import {Group as Groups, GroupSearchCriteria as GroupsSearchCriteria, GroupSearchResults as GroupsSearchResults } from "../../models/Groups";
import GroupsService from "groups/groups.service";

interface ISearchResultsController {
    groups: Groups[];
    groupsSearchCriteria: GroupsSearchCriteria;
    pageChanged(): void;
    splitGroupsPagination(): void;
  }

class SearchResultsController implements ISearchResultsController {

    groups: Groups[];
    groupsSearchCriteria: GroupsSearchCriteria;
    groupresSearchCriteria: any;
    TotalResults: any;
    CurrentPage: any;
    ResultsPerPage: any;
    pageCount: number;
    begin: number;
    end: number;
    sortedResults: Groups[];

           constructor(private groupsService: GroupsService, private groupSearchResults: GroupsSearchResults) {
        var isolatedScopeSearchResults = this;
        this.groups = isolatedScopeSearchResults.groupsService.searchCallback.SearchResults;
        this.groupresSearchCriteria = isolatedScopeSearchResults.groupsService.searchCallback.Criteria;
        this.TotalResults = 7;
        this.CurrentPage = 1;
        this.ResultsPerPage = 5;
    }

    $onInit() {
        this.splitGroupsPagination();
    }

    splitGroupsPagination() {
        this.pageCount = Math.ceil(this.TotalResults / this.ResultsPerPage);
        this.begin = ((this.CurrentPage - 1) * this.ResultsPerPage);
        this.end = this.begin + this.ResultsPerPage;
        this.sortedResults = this.groups.slice(this.begin, this.end);
    }

    pageChanged() {
        this.splitGroupsPagination();
    }
}

export default SearchResultsController;

searchresults.component.ts

    import SearchResultsController from "./searchresults.controller";

    class SearchResultsComponent implements ng.IComponentOptions {
        template = `


    <div id="groupSearchResults" class="box-response">
      <!-- start: results header with btn add-->
        <div class="box-header">
            <h2><span>Search Results: </span><span>{{$ctrl.groups.length}}</span> <span>Term: {{$ctrl.groupresSearchCriteria.SearchDescription}}</span></h2>
        </div>

        <div class="box-content">


    <table class="table table-bordered table-hover table-striped">
        <thead>
            <tr>
                <td>Name</td>
                <td>Id</td>
                <td>Consent Group</td>
                <td>Permitted Uris</td>
                <td>Actions</td>
            </tr>
        </thead>
        <tbody>
            <tr data-ng-repeat="group in $ctrl.sortedResults">
                <td>{{group.Name}}</td>
                <td>{{group.Id}}</td>
                <td>{{group.IncludeInConsentGroups}}</td>
                <td>{{group.PermittedUris}}</td>
                <td>
                   <a class="btn btn-success" href="" ui-sref="edit({editgroupId:group.Id})"><i class="fa fa-edit"></i></a>
                </td>
            </tr>
        </tbody>
    </table>

    </div>

  <uib-pagination total-items="$ctrl.TotalResults" ng-model="$ctrl.CurrentPage" items-per-page="$ctrl.ResultsPerPage" ng-change="$ctrl.pageChanged()"></uib-pagination>

    </div>


       `;

        controller = ['GroupsService',SearchResultsController];
    }

    export default SearchResultsComponent;