Angular Pagination: A Detailed Guide

My goal is to paginate 7 results using a custom pagination tag I created:

<pagination 
            ng-model="currentPage"
            total-items="array.length"
            max-size="maxSize"
            boundary-links="true">
        </pagination>

Below is the code for the controller:

exampleApp.controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
    $scope.currentPage = 1; // 2 - $watch triggers twice
    $scope.numPerPage = 2;
    $scope.maxSize = 5;

    array = $.map(array, function(value, index) {
        return [value];
    });
    $scope.array = array;
    $scope.filteredArray = [];

    $scope.order = function(field) {
      $scope.reverse = ($scope.field === field) ? !$scope.reverse : false;
      $scope.field = field;
    };
    $scope.field = 'id';
    $scope.reverse = false;

    $scope.$watch('currentPage + numPerPage', function() {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage)
        , end = begin + $scope.numPerPage;
        alert(begin + " " + end);
        $scope.filteredArray = $scope.array.slice(begin, end);
    });
}]);

I'm struggling with understanding how Angular calculates the number of pages. With this setup, I only get 1 page instead of the expected 4 pages.

Another issue is that the $watch function triggers twice when manually setting currentPage to 2 or more. The first time it has the correct values, but the second time it reverts to previous ones resulting in failed pagination.

If anyone has any suggestions on how to solve these issues, please let me know.

EDIT:

var exampleApp = angular.module('exampleApp', ['ui.bootstrap']).config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[').endSymbol(']]');
});

exampleApp.controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
    $scope.currentPage = 1;
    $scope.numPerPage = 2;
    $scope.maxSize = 5;

    array = $.map(array, function(value, index) {
        return [value];
    });
    $scope.array = array;
    $scope.filteredCreations = [];

    $scope.order = function(field) {
      $scope.reverse = ($scope.field === field) ? !$scope.reverse : false;
      $scope.field = field;
    };
    $scope.field = 'id';
    $scope.reverse = false;

    $scope.$watch('currentPage + numPerPage', function() {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage)
        , end = begin + $scope.numPerPage;

        $scope.filteredArray = $scope.array.slice(begin, end);
    });
}]);

Partial view:

<div ng-controller="CreationController">
<div class="row" style="text-align: right; margin: 0; padding: 0;">
        <pagination 
            ng-model="currentPage"
            total-items="array.length"
            max-size="maxSize"
            boundary-links="true">
        </pagination>
    </div>
<div class="foobar accordion" ng-repeat="arr in filteredArray | orderBy : field : reverse">
[[arr.id]]
[[arr.name]]
</div>

Answer №1

<div class="baz accordion" ng-repeat="item in filteredData | orderBy : category : ascending|itemsPerPage:7">

Consider including itemsPerPage:7 within your ng-repeat statement.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maximizing for-loop efficiency: the advantage of caching array length

Let's compare two variations of a loop iteration: for (var i = 0; i < nodes.length; i++) { ... } and var len = nodes.length; for (var i = 0; i < len; i++) { ... } Would the second version be faster than the first one in any way? ...

Why doesn't the element I'm clicking return as expected?

Below is the code provided <!DOCTYPE html> <html> <body> <p id="demo">Demo Element</p> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $('#demo' ...

Tips for ensuring the validity of data in an AJAX request

When trying to fetch data using the REST method, I utilize an AJAX call. While my work is completed, I encounter an issue with validating the "data" within the AJAX call. How can I accomplish this? If there is no data returned from the specified URL, it ...

Dividing AngularJS Module Components into Separate Files

I've been working on developing an AngularJS application and I'm currently facing a challenge in creating a reusable module that can be integrated into other projects. The module consists of services and directives that are distributed across sev ...

Is it possible to update a Rails element using an AJAX request?

I've delved into a plethora of information regarding Rails, AJAX, and 5.1 Unobtrusive Javascript. It provides insight on how to handle AJAX calls in Rails with a .js file, for example. However, my goal isn't to serve up an entire .js file; rathe ...

vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error: "Cannot set the property 'days' of undefined" Here is my code snippet: function getDays(date) { this.days = (new Date()).getTime() / ...

An error stating that "DataTable is not a recognized function" occurred within the document function

Previously, I set up datatables using the code below: $(function () { $('#keywords-table').DataTable({ "ajax": ({ url: "{{ route('getKeywordsByProductId') }}", method: "get", ...

I am encountering a problem with IE11 where I am unable to enter any text into my

When using Firefox, I can input text in the fields without any issues in the following code. However, this is not the case when using IE11. <li class="gridster-form" aria-labeledby="Gridster Layout Form" alt="Tile Display Input column Input Row ...

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...

Update the directory path for Angular ui-bootstrap templates

Currently, I am attempting to utilize ui-bootstrap.min.js in conjunction with external templates. An issue has arisen where the error message reads as follows: http://localhost:13132/Place/template/timepicker/timepicker.html 404 (Not Found) I desire fo ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

The body content of the webpage needs to be updated without altering the header and footer, all while avoiding a page

On my website, I have a header menu that includes buttons for "home" and "about us." The default page is set to the home page. Within the home page, there is a specific link. When this link on the home page or the "about us" button is clicked, I want the ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

Providing inputs to $resource

Imagine that we have the following code: angular.factory('Service', [ '$resource', function ($resource) { return $resource('/path/:id', {id: '@id'}); }]) If we use the following code in our controller: v ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

What is the best way to enable editing of a form when the edit button is clicked?

I have created a simple profile page where users can edit their profile information. I have placed a button at the end of the page. Initially, the form should be uneditable, but when the button is clicked, the form becomes editable. I attempted to use `dis ...

"Implementing a method to update an object by its Id within a nested array that includes children, and then managing the state in

How can I dynamically toggle the isExpanded property on click based on an element's ID in a React project? Below is the JSON data structure I am working with const handleExpandOutlineItem = (id: string) => {} This is the structure of my JSON data: ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...

Issue: The GET request to a third-party API using Fetch API encountered a "TypeError: Failed to fetch" error

After conducting extensive research and investing hours into this issue, I am at the point where I need to seek assistance. I am attempting to make a GET call to a third-party Infutor API using the fetch API in my ReactJS Project. Initially, I encountered ...