What is the function of the next and back buttons in AngularJS?

I need assistance with creating next and previous buttons in Angular. As I am new to programming, I have written a program that works when using a custom array $scope.data = []. However, it doesn't work when I use $http and I would appreciate any help in solving this issue.

Controller.js

var app=angular.module('myApp', []);

app.controller('MyCtrl', ['$scope', '$http', '$filter', function ($scope, $filter, $http) {
    $scope.currentPage = 0;
    $scope.pageSize = 2;

    $scope.numberOfPages=function(){
        return Math.ceil($scope.pageSize);                
    }
    
               $http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
          .then(function(response){
            $scope.data = response.data;
          });

}]);


app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

index.htlm

<div ng-app="myApp" ng-controller="MyCtrl">

    <ul>
        <li ng-repeat="item in data  | startFrom:currentPage*pageSize | limitTo:pageSize">
            {{item.title}}
        </li>
    </ul>
    <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button>
    {{currentPage+1}}/{{numberOfPages()}}
    <button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
        Next
  </button>
</div>

Output

Previous {{currentPage+1}}/{{numberOfPages()}} Next

Answer №1

You made a mistake in the dependency sequence when injecting and using them in the controller factory function. Make sure that the injected dependencies are used in the same order as they are injected.

For example, you were injecting '$scope', '$http', '$filter' and using them inside the controller factory function like

function($scope, $filter, $http) {
, where $filter had an instance of $http and $http had an instance of $filter.

app.controller('MyCtrl', ['$scope', '$filter','$http', function ($scope, $filter, $http) {

Answer №2

Keep in mind that the $http request you are making returns an object, not an array. This means you cannot use splice on objects like you do in the filter function. This could be another reason why it is not functioning properly.

Answer №3

Modify this code snippet:

      $http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
      .then(function(response){
        $scope.data = response.data;
      });

Use the following updated code instead. The previous code was returning an object, not an array, so you couldn't apply the splice operation on it. Additionally, the response format didn't match what you are using in $scope.data:

 $http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
      .then(function(response)
{
  var data = [];
  response.data.forEach(function(movieObj, yearKey)
  {
   var temp = {};
   temp.title = movieObj.title;
   temp.id = movieObj.imdbId;
   data.push(temp);
  });
  $scope.data = data;
});

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

Inquiries regarding the distinctive key and component framework of Ant Design

Currently, I am in the midst of a project utilizing react, next.js, and antd. However, an error message has popped up stating: Warning: Each child in a list should have a unique "key" prop. This issue precisely stems from the absence of a uniqu ...

A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response. I'm unsure how to handle this scenario. ...

Reactjs encountering issues with function of Cookies section

Currently, I am working on a login module in Reactjs using Nextjs. Upon successful login, I am storing the user email in a cookie. The functionality is working as expected, but I want to restrict access to the login page for users who are already logged in ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports. $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... }; My challenge is sorting these items by sport name: <ul> ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Safari failing to load JavaScript on live website

While JavaScript functions correctly both locally and in production on Chrome, I am facing issues when trying to run it on Safari. Despite having JavaScript enabled on Safari and it working fine locally, it fails to work on the production environment. This ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

Creating an empty input field with a predetermined default output in ReactJS

My current challenge involves navigating form data between various components in a React application. I am looking to pass data from child components to parent components and vice versa, creating a seamless flow of information. The key requirement is to ha ...

Using jQuery to include Chinese characters in a request header

When making a jQuery post request, I need to set client information in the header. This is how my call looks: jQuery.ajax({ url : myURL, type : "POST", beforeSend : function(request){ request.setRequestHeader('someInfo', clie ...

Trying to figure out how to execute a codeigniter helper function with JQuery AJAX?

I created a handy function in my helper file within codeigniter that formats prices based on the value and currency ID provided. if(!function_exists('format_price')){ function format_price($val,$curency_id=NULL){ $CI ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...

During the execution of a function, the React list remains empty which leads to the issue of having

Having difficulty preventing duplicate values because the item list is always empty when the function is called, even though I know it contains items. The function in question is AddToCart, being passed down to a child component named inventoryModal. The ...

Issue encountered in Wicket Ajax Error Log: ERROR: The listener for the "click" event cannot be bound to the "AjaxCheckBox" element as it is not present in the Document Object Model (DOM)

When running my program, I am trying to dynamically add Panels to the main page and utilize "setVisible(boolean)" functionality. However, I am encountering an error: ERROR: Cannot bind a listener for event "click" on element "institutCheck7" because the ...

Using Express Validator is very easy and efficient once you understand its

Looking for a validator to catch errors and log them to the console Check out the code snippet below: const expressValidator = require('express-validator'); const { check, validationResult } = require('express-validator/check'); const ...

Chrome fails to read font family correctly

I created a jsfiddle that demonstrates an interesting behavior with setting and reading the font-family using jQuery. When I set the font-family to "Arial . . ." it reads back okay, enclosed in a single set of double quotes. However, when I set the font-fa ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...