Tips for effectively navigating search results with pagination

I am struggling to figure out how to conduct an effective search when using pagination. Excuse my poor English writing skills. This is what I have attempted:

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

app.controller('directoryList', function($scope) {
  
  $scope.currentPage = 0;
  $scope.pageSize = 10;
  $scope.users = [{}]
  
  $scope.numberOfPages = function() {
    return Math.ceil($scope.users.length / $scope.pageSize);
  }
  
  for (var i = 0; i < 45; i++) {
    $scope.users.push({
      'name': 'user' + i
    });
  }
});

app.filter('startFrom', function() {
  return function(input, start) {
    start = +start; //parse to int
    return input.slice(start);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="appTelDirectory" ng-controller="directoryList">
  <input placeholder="Search..." ng-model="searchAll" class="form-control">
  <ul>
    <li ng-repeat="item in users | filter:searchAll | startFrom:currentPage*pageSize | limitTo:pageSize">{{item.name}}</li>
  </ul>
  
  <table>
    <tr ng-repeat="item in users | startFrom:currentPage*pageSize | limitTo:pageSize">
  </table>
  
  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">Previous</button>
  
  {{currentPage+1}}/{{numberOfPages()}}
  
  <button ng-disabled="currentPage >= users.length/pageSize - 1" ng-click="currentPage=currentPage+1">
    Next
  </button>
</div>

How can I adjust the number of items based on the user list? The NumberOfPages remains unchanged...

Answer №1

If you want to handle filtering in a different way, you can create a separate list called filteredUsers. Instead of using the filter:searchAll directly in the view, you can utilize the underlying $filter service within a $watch function that triggers as you type.

By storing the filtered users in the filteredUsers variable within the scope, any further operations can now be based on $scope.filteredUsers instead of $scope.users.

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

app.controller('directoryList', function($scope, $filter) {

  $scope.currentPage = 0;
  $scope.pageSize = 10;
  $scope.users = [{}];
  
  // Creating a separate list for filtered users
  $scope.filteredUsers = [{}];

  $scope.numberOfPages = function() {
    return Math.ceil($scope.filteredUsers.length / $scope.pageSize);
  }

  for (var i = 0; i < 45; i++) {
    $scope.users.push({
      'name': 'user' + i
    });
  }

  $scope.filteredUsers = angular.copy($scope.users);

  $scope.$watch('searchAll', function(newValue) {
    // Perform manual filtering here instead of in the view
    $scope.filteredUsers = $filter('filter')($scope.users, {$: newValue});
  });
});

app.filter('startFrom', function() {
  return function(input, start) {
    start = +start; //parse to int
    return input.slice(start);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="appTelDirectory" ng-controller="directoryList">
  <input placeholder="Search..." ng-model="searchAll" class="form-control">
  <ul>
    <li ng-repeat="item in filteredUsers | startFrom:currentPage*pageSize | limitTo:pageSize">{{item.name}}</li>
  </ul>

  <table>
    <tr ng-repeat="item in users | startFrom:currentPage*pageSize | limitTo:pageSize">
  </table>

  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">Previous</button>

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

  <button ng-disabled="currentPage >= filteredUsers.length/pageSize - 1" ng-click="currentPage=currentPage+1">
    Next
  </button>
</div>

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

How can I connect an IDE to my Rails project for better development?

I am interested in incorporating an online terminal or IDE into my Rails application. Is there a method to seamlessly integrate existing IDEs with Rails, or develop a new one specifically for this purpose? I have scoured Google but could not find any rele ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...

What is the best way to avoid HTML code in your text

Currently, I am in the process of developing code with angularjs, node.js, and mongodb to enable users to add comments that will be stored in mongodb through a server operating on node.js. My approach involves substituting < and > with gt and lt. Ho ...

Mysterious AngularJS Error: An Unforeseen Encounter with [$injector:modulerr]

While following a tutorial on creating a MEAN stack project with Google Maps integration, I successfully completed the project without encountering any issues. However, when I returned to check on it later, I discovered that it was no longer functioning pr ...

Is it possible to use JavaScript to clear a field that was generated by Yii CRUD?

Issue with Yii's GRUD field generated and Firefox HTML: <?= $form->field($model, 'productId')->textInput(['maxlength' => true]) ?> Comparison of PHP generated code to Firefox HTML: <input id="taolistforcreate-p ...

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...

Vue: Ensuring one method finishes executing before triggering the next one

I've implemented two methods in my Vue instance; const app = new Vue({ el: '#app', data: { id: null }, methods: { getId: function() { return axios.get('url') .then(response => response.data) .then(i ...

Java and JavaScript - Utilizing a Map

I'm currently using Rhino to run JavaScript code within my Java program, but I've encountered a problem with iterating over the map in JavaScript. On the Java side: private final Map<Long, ClassEmployees > employees ; ... employees.put (n ...

When clicking on an Ajax link inside a partial view, the partial view should be updated

I have a situation where my main view contains a partial view Main view .... .... @if (Model.ProvidedResponseCount > 0) { <div id="providedTimes" data-url="@Url.Action("ProvidedAttendeeResponse", new { attendeeId = @Model.AttendeeId })"> ...

Bring your Electronic Catalogue to life with the addition of dynamic HTML content showcasing the latest

I am creating a digital magazine but I am facing the challenge of having to deal with 200 pages in jpg format. To streamline the process, I am looking for a way to use a combination of JavaScript and PHP to avoid manually coding for each of the 200 pages. ...

AngularJS directive that handles async parameters within the scope

Creating a directive to simplify access to static data in my app is proving to be quite the challenge. Within my $rootScope, I have a params object that holds static data retrieved from the backend server. The objective of this directive is to make it easi ...

AngularJS UI router allows for the creation of sticky states, where each state maintains its own instance of the controller even when

Currently, I am in the process of developing a CMS with a tabular structure using AngularJS. The main functionality is to allow users to open and edit multiple articles within tabs. Each article is handled by the articleController and has different URL par ...

How to Properly Manipulate DOM Elements in an Angular Directive

My directive, powerEntry, has different CSS classes that I want to add or remove based on the model state. Currently, in my link function, I have some logic like this: Script.JS if (calcState.availablePoints > 0 && isHighEnoughLevel) { ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

What is the process for sending a message from the internet to a mobile device?

We are currently in the process of developing a website that sends SMS alerts to users for specific services, however I am struggling to set up a script that can perform this function. If anyone has any suggestions or recommendations for a solution, pleas ...

Unable to communicate with the server-side controller using Angular

Encountering issues when attempting to call a server-side controller using AngularJS, these two error messages are being displayed. The parameters dictionary contains a null entry for parameter 'problemId' of non-nullable type 'System.Guid& ...

Obtain the value of "data-something" attribute from an <option> element within a <select> element

Can anyone help me with this HTML snippet? <select id="something"> <option value="1" data-something="true">Something True</option> <option value="2" data-something-else="false">Something Else False</option> </selec ...

The Angular single-spa.js framework is altering the URLs of deep imports to localhost

I am currently utilizing the single-spa library (version 5.8.2) in conjunction with multiple Angular projects. Upon attempting to import ngx-quill (a library that itself imports another library, quill.js), I encountered an issue where the single spa librar ...

Attempting to pass a value to a data table using the Tabulator library within a Laravel 5.4 environment

Currently, I am trying to pass a value from a controller to a view in the following manner: use App\Products; use Illuminate\Http\Request; class MyController extends Controller public function index() { $main = Products::all(); ...

Running a callback in a CucumberJS step definition utilizing Selenium

Currently, I'm exploring CucumberJS with Selenium and PhantomJS. With the help of a helpful StackOverflow answer, I've successfully built a World object to guide me through. Now, as I delve into testing basic step definitions, I find myself conf ...