Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues

Code

var app = angular.module("MyApp", []);

app.filter('offset', function() {
  return function(input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});

app.controller("MyControler", function($scope, $http, $filter) {
      $http.get("http://127.0.0.1:8000/cars/?format=json").
        success(function(data) {
              $scope.list = data;
          });

  $scope.itemsPerPage = 1;
  $scope.currentPage = 0;
  $scope.items = [];

  for (var i=0; i<50; i++) {
    $scope.items.push({ id: i, name: "name "+ i, description: "description " + i });
  }

  $scope.range = function() {
    var rangeSize = 3;
    var ret = [];
    var start;

    start = $scope.currentPage;
    if ( start > $scope.pageCount()-rangeSize ) {
      start = $scope.pageCount()-rangeSize+1;
    }

    for (var i=start; i<start+rangeSize; i++) {
      ret.push(i);
    }
    return ret;
  };

  $scope.prevPage = function() {
    if ($scope.currentPage > 0) {
      $scope.currentPage--;
    }
  };

  $scope.prevPageDisabled = function() {
    return $scope.currentPage === 0 ? "disabled" : "";
  };

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

  $scope.nextPage = function() {
    if ($scope.currentPage < $scope.pageCount()) {
      $scope.currentPage++;
    }
  };

  $scope.nextPageDisabled = function() {
    return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
  };

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


  var filterBy = $filter('filter');
  $scope.$watch('search', function (newValue) { $scope.filtered = filterBy($scope.list, newValue); }, true);

});
<!DOCTYPE html>
        {% load staticfiles %}
<html>
<head lang="en">
    <meta charset="UTF-8>
    <title></title>



</head>
<body>

{% verbatim %}

  <div ng-app="MyApp" ng-controller="MyControler">
    <table class="table table-striped">
      <thead>
            <tr>
        <th><input ng-model="search.name" ></th>
        <th><input ng-model="search.years"></th>
        <th><input ng-model="search.owners"></th>
        <th><input ng-model="search.accidents"></th>
        <th><input ng-model="search.description"></th>
    </tr>
        <tr>

          <th>Name</th>
              <th>Years</th>
          <th>Owners</th>
              <th>Accidents</th>
            <th>Description</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="cars in filtered| offset:currentPage*itemsPerPage | limitTo: itemsPerPage">

          <td>{{cars.name}}</td>
          <td>{{cars.years}}</td>

          <td>{{cars.owners}}</td>
          <td>{{cars.accidents}}</td>

          <td>{{cars.description}}</td>

        </tr>
      </tbody>
      <tfoot>
        <td colspan="3">
          <div class="pagination">
            <ul>
              <li ng-class="prevPageDisabled()">
                <a href ng-click="prevPage()">« Prev</a>
              </li>
              <li ng-repeat="n in range()" ng-class="{active: n == currentPage}" ng-click="setPage(n)">
                <a href="#">{{n+1}}</a>
              </li>
              <li ng-class="nextPageDisabled()">
                <a href ng-click="nextPage()">Next »</a>
              </li>
            </ul>
          </div>
        </td>
      </tfoot>
    </table>
  </div>


{% endverbatim %}
</body>

 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <script src="{% static 'js/app2.js' %}"></script>
</html>

When I type into the filter field, my objects only then get displayed. After pagination is updated actively with typing, something strange happens - the pagination displays pages with minuses?

I want to show items without having to start typing into the filter and make those minuses disappear.

Thank you ;)

Answer №1

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

app.controller("MyControler", function($scope, $http, $filter) {
      $http.get("http://127.0.0.1:8000/cars/?format=json").
        success(function(data) {
              $scope.list = data;
          });
    $scope.currentPage = 0;
    $scope.pageSize = 1;


    $scope.numberOfPages=function(){
        var myFilteredData = $filter('filter')($scope.list, $scope.search);
        return Math.ceil(myFilteredData.length/$scope.pageSize);
    };

});


app.filter("offset", function() {
    return function(input, start) {
        start = +start;
        return input.slice(start);
    };
});
<!DOCTYPE html>
        {% load staticfiles %}
<html>
<head lang="en">
    <meta charset="UTF-8>
    <title></title>



</head>
<body>

{% verbatim %}

  <div ng-app="MyApp" ng-controller="MyControler">

        <table>
            <tr>
        <th><input type="text" ng-model="search.name" class="form-control input-sm" placeholder="SEARCH" ></th>
        <th><input type="text" ng-model="search.years" class="form-control input-sm" placeholder="SEARCH"></th>
        <th><input type="text" ng-model="search.owners" class="form-control input-sm" placeholder="SEARCH"></th>
        <th><input type="text" ng-model="search.accidents" class="form-control input-sm" placeholder="SEARCH"></th>
        <th><input type="text" ng-model="search.description" class="form-control input-sm" placeholder="SEARCH"></th>
    </tr>
        <tr>

          <th>Name</th>
              <th>Years</th>
          <th>Owners</th>
              <th>Accidents</th>
            <th>Description</th>
        </tr>

        <tr ng-repeat="cars in list | filter:search|offset:currentPage*pageSize | limitTo:pageSize">

                    <td>{{cars.name}}</td>
          <td>{{cars.years}}</td>

          <td>{{cars.owners}}</td>
          <td>{{cars.accidents}}</td>

          <td>{{cars.description}}</td>

        </tr>
      </table>


    <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button>
    
    {{currentPage+1}}/{{numberOfPages()}}
    <button ng-disabled="(currentPage + 1) == numberOfPages()" ng-click="currentPage=currentPage+1">
        Next
    </button>

  </div>


{% endverbatim %}
</body>

 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <script src="{% static 'js/app2.js' %}"></script>
</html>
Answer Verified

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

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...

Is it possible to send a variable to the controller through UI-Router and ui-sref?

Is it possible to pass multiple variables through the UI-Router for use in a state's controller? In the HTML, I have <li class="blist-item grid-loader" ng-repeat="item in items"> <a ui-sref="item({ id: {{item.$id}} })"><h3>{{it ...

Adding HTML content to a DOM element using Angular

Looking to create a directive that can dynamically append HTML content within a div element. Specifically, I need this directive to handle HTML data fetched from the server using an $http post request. <div id="invoice_template_preview" ng-bind-h ...

Transform an array of strings into an array of object IDs

Recently, I encountered an issue with transforming an array of strings into object IDs using mongoose type. Unfortunately, my attempt was unsuccessful as it seems the method only works for single string inputs, not arrays. let stringObjectIdArray = [&apos ...

The boxslider plugin is malfunctioning when accessed in Sitecore's preview mode

Even though the Boxslider plugin works when we view the page in a browser, it fails to function properly when the same page is viewed in Sitecore's Preview mode. This issue can be replicated by navigating to Presentation in the top menu, then selectin ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

JSON object containing elements with dash (-) character in their names

While I am in the process of parsing a `json` object, I encountered an element labeled as `data-config`. Here's an example: var video = data.element.data-config; Every time I attempt to parse this specific element, an error pops up: ReferenceError ...

Tips for displaying a div briefly before loading the second page

Incorporating a div named ADD, I aim to successfully load a second page within the current one using ajaxload. The challenge lies in displaying a div for 4 seconds before loading the second page. How can this be achieved? Following the wait period, the sec ...

Dealing with multipart/form-data in Express using cloud functions in the upcoming year of 2022

Seeking advice on handling multipart/form-data requests in an Express backend with Google Cloud Functions in 2022. Despite numerous attempts, the issue remains unresolved after extensive research and testing various methods that work locally but fail when ...

jQuery will envelop the HTML elements in an inconsequential div

Imagine a website that is visually complex, with various styles and images positioned in different ways. What if we wanted to add a small overlay icon above each image? At first, the solution might seem simple - just use absolute positioning for a span el ...

AngularJS - Alter the URL with $state.go without refreshing the HTML content

Struggling with routing in angularJS and can't seem to find a solution despite trying various methods online. Any assistance would be greatly appreciated. Encountering an issue with the $state.go function in which it changes the URL but fails to load ...

[Babel]: The option foreign.Children is not recognized

I encountered an error while building with the following script: webpack --colors --progress --watch --config --jsx-loader webpack.config.js Below is the content of my package.json file: { "dependencies": { // List of dependencies here }, "dev ...

Issue with the positioning of the datepicker is not functioning properly

I'm currently facing an issue with the position of a date picker plugin from jquery. The search box on my website allows users to select a range of dates using the date picker, but when enabled, the date picker appears at the bottom left corner of the ...

Maintaining aspect ratio of canvas while ensuring responsiveness

Currently, I am working on a drawing app and have come across an issue that has been challenging for me to resolve. The dilemma lies in resizing the canvas of sketches from the original resolution of 1280 x 720 to the maximum size possible upon opening the ...

Creating a dynamic dropdown menu in HTML to showcase a variety of images

I am trying to create a drop down menu where each selection displays multiple elements. For example, if sensor 1 is chosen, I want to show a picture of its location and its address. I am having trouble figuring out how to add these functions to the drop ...

Navigating in Angular is easy when you understand how to use special characters such as

In order to set a unique path in AngularJS routing, I am looking for the following features: An optional parameter The ability to accept values of a relative path Here are some examples of the parameter values I need to work with: /ABC /ABC/123 /ABC/12 ...

What method does jQuery Validation use to configure the validation message?

A custom method was developed for the jQuery validation plugin to validate whether a given value meets the length requirements set during validation. The method is structured as follows: jQuery.validator.addMethod("exactLength", function(value, ...

Angular backslash is encoded

Experiencing the same issue as this individual: angularjs-slash-after-hashbang-gets-encoded The URL is getting encoded and not routing correctly, causing it to fall to the otherwise in my route config. I have not been able to identify the root cause yet, ...

Express session not persisting following JQuery Get request

I need to save the server variable that the user inputs. Once they submit, they are directed to another page. On this new page, I check if their server exists and redirect them back if it doesn't. When I make a post request, the session is saved, and ...