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

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

The ng-class index is malfunctioning

Seeking help with troubleshooting the following code: <div> <table class="list" border="0" cellpadding="0" cellspacing="0"> <thead> <tr class="headerRow"> ...

Iterate endlessly over CSS styles in Angular 4

I'm looking to create a website background 'screensaver' by looping through an array of background URLs with a delay between switches. Currently, I have the array stored in my .ts file and I am using the NgFor directive in my HTML. However, ...

Symfony/AngularJS Blocked Cross-Origin Request

I am currently encountering an issue while attempting to retrieve data using Angular from my Symfony API, which returns JSON: "Cross-Origin Request Blocked: The Same Origin Policy prohibits reading the remote resource at http://localhost:8000/custom ...

Sending data from an AngularJS frontend to a Laravel backend using an HTTP

I've been researching, but I can't seem to make sense of anything. I'm new to Laravel and I want to use it as a backend for my AngularJS project. Since I have experience with Angular, here is the controller function where I make an HTTP call ...

Display the JSON data in a table by utilizing the ng-repeat directive in Angular

Below is the response that I have: Response : response: {"json": {"response": {"servicetype":"", "functiontype":"", "statuscode":"0", "statusmessage":"Success", "data":[{"graphtype":"piechart", "xlabel":"state", "ylabel":"count", "s1":"contact", "s2":" ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Enhance your application by utilizing additional hooks in the Context API

I'm exploring API and react hooks and have a query related to dispatching API fetch to ContextAPI component. Is there a way to consolidate all useState hooks into a single ContextAPI component? The objective is code refactoring by breaking it down int ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Managing user sessions in Node.js

What is the best way to manage SESSIONS in Node.js? Specifically, I am interested in storing a UserID in a session using Node.js. How can this be accomplished, and is it possible to access that Node.js session in PHP as well? I am looking for an equivale ...

Step-by-step guide on retrieving JSONP data from Angular service within view by utilizing expressions

I have been developing an Angular application that retrieves data from the Strava API. While experimenting with $http.get, I realized that separating the logic into a dedicated service would be more organized, allowing my controller to simply call the serv ...

Troubles with retrieving Array data for a JavaScript column chart

I am currently developing a Flask app in Python and utilizing render_template to send back 2 arrays, "names" and "deals", to my HTML file. I have confirmed that these arrays are working correctly based on the code snippet below that I tested, which display ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

Precise coordination of a singular model through the use of angularFireCollection

I am currently using version 0.3.0 of angularFire in order to connect an AngularJS application to Firebase. My goal is to achieve explicit synchronization of a single model on an edit form. After referring to the documentation, I attempted to utilize angu ...

Discover the secrets to replicating the mesmerizing horizontal scrolling menu akin to the

What is the most effective way to create a horizontal menu similar to the innovative Google picture menu? Could someone kindly share their knowledge and provide the code for achieving the same outcome? ...

Different ways to display a static content list using Vue's named slots

I'm struggling to make the following setup work: My parent template <comp> <a href="#" slot="links">link 1</a> <a href="#" slot="links">link 2</a> </comp> and in my comp ...

Trouble with Component Lifecycle (ComponentDidMount) activation while switching tabs in TabBar?

After implementing the react-native-tab-navigator library to navigate between components, I encountered an issue where the componentDidMount lifecycle method works only once. I have reached out for help by posting a query on Github and have also attempted ...