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

What steps should I take to fix an error in my code?

My current objective is to write a program that generates a square with dimensions of 200 pixels by 200 pixels. The square should be colored using specific RGB values: red (red value of 255), green (green value of 255), blue (blue value of 255), and magent ...

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

What are the methods for integrating a JavaScript framework in a Rails application without utilizing any gems?

I am seeking guidance on integrating frameworks such as angularjs, polymer js, bootstrap, etc., into a Rails application without relying on corresponding gems. The reason for this approach is that the availability of gems may change and some projects may ...

Tips for managing, showcasing, and modifying checkbox controls within an AngularJS environment

I have successfully completed the saving part of the code. Below, I am demonstrating how I displayed the saved data and my attempts to edit the form upon clicking the edit button. Here is my AngularJS code: var module = angular.module('myApp&apos ...

The hover effect is not functioning upon loading

Demo: http://jsbin.com/afixay/3/edit 1) Hover over the red box. 2) Without moving the cursor, press ctrl+r to reload the page. 3) No alert will appear. However, an alert will pop up once you move the cursor away and hover back over the box. The issue h ...

Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory: import Vuex from "vuex"; const createStore = ...

A more efficient method for refreshing Discord Message Embeds using a MessageComponentInteraction collector to streamline updates

Currently, I am working on developing a horse race command for my discord bot using TypeScript. The code is functioning properly; however, there is an issue with updating an embed that displays the race and the participants. To ensure the update works co ...

Implementing automatic dark mode activation during nighttime with jQuery or JavaScript

I'm looking to implement an automatic dark mode feature on my website that switches on at night and off during the day or morning. Currently, my website has a dark mode toggle code that allows users to switch between dark and light modes using local ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...

CSS Element Overlapping Issue in Safari Browser

I am currently developing an audio player for my application that includes a pause/play button, next button, and back button. I have encountered a problem specifically on Safari where the back/pause buttons are overlapping each other. The play/pause button ...

Calculating the Bounding Box of SVG Group Elements

Today I encountered a puzzling scenario involving bounding box calculations, and it seems that I have yet to fully understand the situation. To clarify, a bounding box is described as the smallest box in which an untransformed element can fit within. I h ...

Unlocking CORS on DIVSHOT: A Step-by-Step Guide

I've encountered a challenge with the Access-Allow-Control-Origin issue while using Divshot. My mobile app is designed to display posts from a WordPress account, and while testing in a browser I can see the posts without any problem. However, when I t ...

Dynamic Bootstrap Popover: Creating interactive popups by dynamically attaching events to buttons

I am looking to implement the Bootstrap Popover module to create a confirmation dialog for a delete action. When a <button> is clicked, instead of immediately executing a function, I want a popup to appear allowing the user to either confirm or dismi ...

The filter function in JavaScript's Array is malfunctioning on Internet Explorer version 7

My web application includes a jQuery plugin that is functioning correctly in Internet Explorer 10 and 11. However, it is not working in IE 7. Upon investigation, I discovered that the value of the filter method is showing as undefined. The line of code th ...

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

Updating a session or global variable cannot be read by an AJAX request

Currently using Flask with google-python-api-client for fetching data from Youtube. Experimenting with loading the next video asynchronously from the playlist upon button click. To achieve this, setting the nextPageToken parameter in the request is essent ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

In JavaScript, constructors do not have access to variables

Currently, I am attempting to implement Twilio Access Token on Firebase Functions using TypeScript. export const generateTwilioToken = functions.https.onRequest((req, res) => { const twilioAccessToken = twilio.jwt.AccessToken; const envConfig = fun ...

Is it possible to request/scrape pages from the client side?

Let me present the issue at hand: I am currently managing a web application that serves as a notification system which updates frequently. This application is operational on several local computers, each of which solely display information without any inp ...