How to implement sorting and filtering in AngularJS tables



Image not found!!

Implementing sorting and filtering in AngularJS tables involves using AngularJS directives and filters. Here's a basic example of how you can achieve this:

  1. Setup your AngularJS Application: First, make sure you have AngularJS included in your project.
html
<!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>AngularJS Sorting and Filtering</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body> <div ng-controller="myController"> <input type="text" ng-model="search" placeholder="Search..."> <table> <thead> <tr> <th><a href="#" ng-click="sortType = 'name'; sortReverse = !sortReverse">Name</a></th> <th><a href="#" ng-click="sortType = 'age'; sortReverse = !sortReverse">Age</a></th> </tr> </thead> <tbody> <tr ng-repeat="person in people | orderBy:sortType:sortReverse | filter:search"> <td>{{ person.name }}</td> <td>{{ person.age }}</td> </tr> </tbody> </table> </div> <script> var app = angular.module('myApp', []); app.controller('myController', function ($scope) { $scope.people = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Doe', age: 20 }, ]; $scope.sortType = 'name'; $scope.sortReverse = false; }); </script> </body> </html>

In this example:

  • ng-repeat is used to loop through the list of people.
  • orderBy filter sorts the people based on the property specified by sortType and the order specified by sortReverse.
  • filter filter filters the people based on the search query entered in the input box.
  1. Create the AngularJS Controller: Define an AngularJS controller and initialize the scope with data and sorting/filtering options.

  2. HTML Structure: Set up the HTML structure for your table and include necessary AngularJS directives (ng-repeat, ng-click, ng-model) to handle sorting, filtering, and data binding.

  3. Sorting: Use orderBy filter to sort the data based on a specified property (sortType) and direction (sortReverse).

  4. Filtering: Utilize the filter filter to filter data based on a search query (search).

This is a basic example to get you started. Depending on your specific requirements, you may need to implement more advanced features or customize the implementation further.