Issue detected in AngularJS 1.6 app: Attempting to convert pagination of items into a service results in failure

Currently, I am developing a compact Contact application using Bootstrap 4 along with AngularJS v1.6.6.

This application is designed to showcase a JSON file containing various user data. Considering the large dataset in the JSON, the app features a pagination system for ease of navigation.

Initially, the pagination functioned as expected within the controller. However, upon attempting to convert it into a service, it ceased to work properly.

To view a working version with the pagination integrated within the controller, click HERE.

The current implementation comprises of:

// Defining an Angular module named "contactsApp"
var app = angular.module("contactsApp", []);

// Creating the controller for "contactsApp" module
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
  var url = "https://randomuser.me/api/?&results=100&inc=name,location,email,cell,picture";
  $scope.contactList = [];
  $scope.search = "";
  $scope.filterList = function() {
    var oldList = $scope.contactList || [];
    $scope.contactList = $filter('filter')($scope.contacts, $scope.search);
    if (oldList.length != $scope.contactList.length) {
      $scope.pageNum = 1;
      $scope.startAt = 0;
    };
    $scope.itemsCount = $scope.contactList.length;
    $scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
  };

  $http.get(url)
    .then(function(data) {
      // storing contacts array
      $scope.contacts = data.data.results;
      $scope.filterList();

      // Incorporating Pagination Service
      $scope.paginateContacts = function(){
        $scope.pagination = paginationService.paginateContacts();
      }

    });
}]);

The service section contains:

app.factory('paginationService', function(){
     return {
        paginateContacts:  function(){
            // Pagination logic
            $scope.pageNum = 1;
            $scope.perPage = 24;
            $scope.startAt = 0;
            $scope.filterList();

            $scope.currentPage = function(index) {
                $scope.pageNum = index + 1;
                $scope.startAt = index * $scope.perPage;
            };

            $scope.prevPage = function() {
                if ($scope.pageNum > 1) {
                    $scope.pageNum = $scope.pageNum - 1;
                    $scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
                }
            };

            $scope.nextPage = function() {
                if ($scope.pageNum < $scope.pageMax) {
                    $scope.pageNum = $scope.pageNum + 1;
                    $scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
                }
            };
        }
    }
});

Incorporation within the view:

<div ng-if="pageMax > 1">
        <ul class="pagination pagination-sm justify-content-center">
            <li class="page-item"><a href="#" ng-click="prevPage()"><i class="<fa fa-chevron-left"></i></a></li>
            <li ng-repeat="n in [].constructor(pageMax) track by $index" ng-class="{true: 'active'}[$index == pageNum - 1]">
                <a href="#" ng-click="currentPage($index)">{{$index+1}}</a>
            </li>
            <li><a href="#" ng-click="nextPage()"><i class="<fa fa-chevron-right"></i></a></li>
        </ul>
</div>

Confirming that the service file is appropriately included after the app.js:

<script src="js/app.js"></script>
<script src="js/paginationService.js"></script>

As I am not proficient in AngularJS, could you guide me on what might be lacking?

Answer №1

It seems that in order for the injection to work properly, the service must be defined before the controller.

You have two options: either move the paginationService into app.js:

var app = angular.module("contactsApp", []);
app.factory('paginationService', function(){
    //...
});
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
    //...
});

Alternatively, you can separate the controller into a different file that is included after the paginationServices.js file.

Check out this plunker. Try editing line 6 by removing character 5 - the space between the star and slash that closes the multi-line comment.

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

Organize an array of objects with underscore.js to arrange them in a

I have an array of objects that looks like this: profData=[{"Details":{"CODE":"PAT4PAS","DESCRIPTION":"PASTIE 4N20 12 X 175G","LOCATION":"FREEZER","UNITS":"BOX","WAREHOUSE":"00","AVAILABLE":"15.0000","ON_HAND":"15.0000","BRAND":"4N20","PRICE1":"18.80"," ...

Which characters are permissible for the id attribute to prevent the jQuery selector from throwing an exception?

I am facing a situation where the id attribute is inputted by an end user. For instance, if the id for a textbox is "11_=11" as entered by the user, then the HTML code will appear like this: <input type="text" id="11_=11"> The corresponding jQuery ...

Can existing servers support server side rendering?

I am currently working on building a Single Page Application (SPA) using the latest Angular framework. The SPA will involve a combination of static HTML pages, server side rendering, and possibly Nunjucks templating engine. My dilemma lies in the fact th ...

Examining a webpage using the headless mode of the webkit rendering engine

I am encountering an issue while trying to utilize the django-wkhtmltopdf wrapper for wkhtmltopdf executable, which employs the webkit rendering engine to convert HTML pages to PDF. My web pages were developed with a focus on Chrome and Firefox, containing ...

Is it possible to dynamically assign a CSS class to a DOM element during a drag operation while the mouse button is held down?

I am currently working on developing a unique pathfinder visualizer. My progress so far includes creating a grid of size 16x45 using the function below: export const drawBoard = () => { const boardContainer: HTMLDivElement | null = document.querySelec ...

"Exploring the functionalities of Expressjs's bodyParser and connect-form

I am encountering issues when trying to upload images using a connect form. It seems that the bodyParser() is causing problems with the upload process. Conversely, if I do not use bodyParser, I am unable to upload files. How can I resolve this issue and ...

Automatically increase the dates in two cells once they have passed

Summary: Although I'm not a programmer, I've managed to incorporate some complex coding into a Google Sheets document for tracking my team's projects. This includes multiple-variable dropdown menus and integration with Google Calendar to mo ...

Combining Protractor, CucumberJS, and Gulp-Protractor results in the browser not closing when a test fails

Hello! I am facing an issue with closing the browser when a test fails. Currently, the browser closes successfully when the test passes. The dependencies I am using are: "cucumber": "^0.9.2", "gulp": "~3.9.0", "gulp-protractor": "^2.1.0", "protractor": ...

implementing jqBarGraph on my webpage

Hey there! I have been trying to add a graph to my HTML page for quite some time now. After doing some research, I discovered that using the jqBarGraph plug-in makes it easier to create the desired graph. Below you will find the code that I have on my webp ...

Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side: const leaderboard = [[dog,cat],[car,bus],[foo,bar]] const toJson = JSON.stringify(leaderboard) res.render('gam ...

Using ajax to submit a request to the controller

I'm currently developing an ASP.NET Core MVC application and have a registration page set up. My goal is to return View with errors if the model state is false: @model WebApplication2PROP.Entities.UserRegister @* For more information on enabling M ...

In Firefox, the CSS height and width values are displayed as X pixels, whereas in Internet Explorer, they are automatically set to 'auto'

When it comes to measuring div box dimensions, jQuery can be a handy tool. Here is an example code snippet: $(document).ready(function(){ var h = $("#testbox").css("height"); }); Interestingly, the same code can give different results in different brow ...

Refreshing DataTables with specific parameters using ajax.reload()

In my Angular2 project, I am utilizing DataTables with the serverSide feature. After making changes, I am attempting to reload the table and pass these changes as parameters in a POST request via AJAX. The issue I am encountering is that DataTables alway ...

Dealing with errors in external URLs with AngularJS: A guide to intercepting errors in $resource or $http services

I have set up a separate server for my angularjs app, which is different from my grunt server. This external server runs on Apache and uses PHP to serve JSON data. I want to be able to catch any potential server errors, ranging from "server down" to "404". ...

Tips on eliminating the letter 'X' from a text/search input field in HTML

There are various solutions available for removing the "X" from an input field in IE 10+ browsers. I have tried multiple approaches without success. For example, I have referenced: ans 1 ans 2 ans 3 Despite implementing all of these solutions, I still ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

What is the most strategic way to conceal this overlay element?

Currently, the website I'm developing features a series of navigation elements at the top such as "Products" and "Company." Upon hovering over the Products link, an overlay displays a list of products with clickable links. Positioned at the top of the ...

Including a pfx certificate in an Angular $http request

My current challenge involves utilizing an external API located at https://example.com/. Upon attempting to access this API, a prompt appears requesting a certificate. Fortunately, I possess the necessary .pfx file or it may be stored in my keychain as a . ...

What is the process of generating a dynamic card/button element on an ASP.net webpage using information from the backend database?

I'm faced with a challenge of displaying employees' names and titles from a MSSQL Server database table on an ASP .NET webform as individual "card" objects. Currently, I am able to showcase a static number of records by using an asp button object ...

Transferring information through AJAX to the current page using a foreach loop in Laravel 5

As a newcomer to ajax and laravel 5, I am eager to learn how to pass data with ajax to populate a foreach loop in laravel 5 on the same page. <div class="row" style="margin:3% 0px 0px 0px"> @foreach($warung_has_kategoriwarungs['i want pass ...