In this blog, I'm going to show you how to create a simple table like a datatable kind of functionality using AngularJS.
Like jQuery DataTable, my demo also includes,
- Sorting By Name
- Searching of Data
For that, I have used AngularJS script file as followed.
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
And also, I have used some of the bootstrap script and style files
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Some of the Angular concepts that I have used are listed below.
- ng-app - Tells that it is a root element of AngularJs Application
- ng-controller - Invokes by $Scope
- ng-model - Binds input field to a variable
- ng-click - Defines what we should do when an element is clicked
Here, you can find the source code of what I have developed.
- <body>
- <div class="container">
- <div ng-app="myApp" ng-controller="namesCtrl" ng-init="IsReverse=false">
- Search: <input type="text" ng-model="test"><br>
- <table class="table table-hover table-bordered table-striped">
-
- <tr>
- <th ng-click="sort('Name')">Name
- <th ng-click="sort('Age')">Age
- <th ng-click="sort('Email')">Email
- <th>Actions</th>
- </tr>
- <tr ng-repeat="x in names | filter:test | orderBy:sortParam:IsReverse">
- <td>{{x.Name}}
- <td>{{x.Age}}
- <td>{{x.Email}}
- <td>
- <div class="btn-group">
- <a class="btn btn-primary" href="#">EDIT</a>
- <a class="btn btn-primary" href="#">DELETE</a>
- </div>
- </td>
- </tr>
- </table>
-
- </div>
-
- <script>
- angular.module('myApp', []).controller('namesCtrl', function($scope) {
-
- $scope.names = [
- {Name:'Manav',Age:'22',Email:'[email protected]'},
- {Name:'Rahul',Age:'25',Email:'[email protected]'},
- {Name:'Rohan',Age:'28',Email:'[email protected]'},
- {Name:'Jinish',Age:'18',Email:'[email protected]'}
- ];
-
- $scope.sort = function(sortId) {
- $scope.sortParam = sortId;
- if($scope.IsReverse)
- {
- $scope.IsReverse = false;
- }
- else
- {
- $scope.IsReverse = true;
- }
-
- };
-
- });
- </script>
- </body>
As you can see, the Controller will be invoked by calling Using.
- controller('namesCtrl', function($scope)
Primary output of my code is as follows:
And for searching , you can see output after I have searched "Manav;" the data will be filtered :
That's all for now. You can try and enhance it by adding more functionality like pagination or total item count etc.
Thanks for reading.