Scrollx hide search inputs - datatable

I have a little problem.
When adding my table the element "scrollX": true, the search entries disappear.
CODE:
JAVASCRIPT
function parametrosTabla6(tabla) {
var tabla2 = $(tabla).DataTable({
'paging': true,
'searching': true,
'ordering': true,
'orderCellsTop': true,
'order': [
[0, 'desc']
],
"scrollX": true,
'columnDefs': [
{
'responsivePriority': 1,
'targets': 0
},
{
'responsivePriority': 2,
'targets': -1
},
{ "className": "dt-center", "targets": "_all" }
],
'responsive': true,
});
var len = $('#datos thead tr:eq(1) th').length;
$('#datos tfoot:eq(0) th').each(function (i, e) {
var title = $(this).text();
if (i == len - 1) { } else {
$(this).html('<input style="width:100%" class="form-control" data-column="' + (i + 1) + '" type="text" placeholder="' + title + '" />');
}
$('input', this).on('keyup change', function () {
if (tabla2.column(i).search() !== this.value) {
tabla2.column(i).search(this.value).draw();
}
});
});
}
HTML/CSS/PHP
<table id="datos" class="table table-hover display drtresponsive nowrap" width="100%">
<thead>
<th>Nº Pedido</th>
<th>Cliente</th>
<th>Nº Telefono (fijo-movil)</th>
<th>Fecha Venta</th>
<th>Correo Enviado</th>
<th>Estado Pago</th>
<th>Expedicion</th>
<th>Fecha Envio</th>
<th>Fecha Entrega</th>
<th>Recibido</th>
<th>Anulado</th>
<th>Usuario Venta</th>
<th>Ultimo usuario editado</th>
<th>Acciones Disponibles</th>
</thead>
<tfoot style="display: table-header-group">
<tr>
<th>Nº Pedido</th>
<th>Cliente</th>
<th>Nº Telefono (fijo-movil)</th>
<th>Fecha Venta</th>
<th>Correo Enviado</th>
<th>Estado Pago</th>
<th>Expedicion</th>
<th>Fecha Envio</th>
<th>Fecha Entrega</th>
<th>Recibido</th>
<th>Anulado</th>
<th>Usuario Venta</th>
<th>Ultimo usuario editado</th>
<th>Acciones Disponibles</th>
</tr>
</tfoot>
<tbody>
<?php
if (isset($result)) {
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
switch ($row['recibido']) {
case 0:
$row['recibido'] = "NO";
break;
case 1:
$row['recibido'] = "SI";
break;
}
switch ($row['correo_confirmacion']) {
case 0:
$row['correo_confirmacion'] = "NO";
break;
case 1:
$row['correo_confirmacion'] = "SI";
break;
}
switch ($row['factura']) {
case 0:
$row['factura'] = "NO";
break;
case 1:
$row['factura'] = "SI";
break;
}
switch ($row['anulado']) {
case 0:
$row['anulado'] = "NO";
break;
case 1:
$row['anulado'] = "SI";
break;
}
require 'mod/tabla_facturas.php';
}
} else {
echo "<tr>0 results</td>";
}
} else {
echo "<td colspan='100%'>0 results</td>";
}
?>
</tbody>
</table>

Here is the answer.
You have two options:
(The one I have chosen) Put the overflow-x:auto in parent div.
Clone the thead and add the inputs.
var len = $('#datos thead tr:eq(1) th').length;
$('#datos thead tr').clone(true).appendTo('#datos thead');
$('#datos thead tr:eq(1) th').each(function (i, e) {
var title = $(this).text();
if (i == len - 1) {
} else {
$(this).html('<input style="width:100%" type="text" placeholder="' + title + '" />');
}
$('input', this).on('keyup change', function () {
if (table.column(i).search() !== this.value) {
table
.column(i)
.search(this.value)
.draw();
}
});
});
Add the orderCellsTop option to the datatable.

Related

Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

Filter records using daterangetime picker

I have a target where I need to filter the data using daterange with time picker. The thing is I need to show the result of my filtered data based on what I selected on the said daterange with time picker I have provided my codes below and my target. Thank you so much in advance.
Views:
<div class="card-body table-responsive py-3 px-3">
<input type="text" id="demo" name="daterange" value="06/05/2021 - 06/06/2021" style="width:350px;">
<button class="btn btn-success float-right" onclick="add_person()" data-dismiss="modal"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
<table id="table_account" class="table table-bordered table-hover" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Mobile</th>
<th>Role</th>
<th>Status </th>
<!-- <th>File </th> -->
<th>Added By</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Updated By</th>
<th style="width:100x;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</script>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Mobile</th>
<th>Role</th>
<th>Status </th>
<th>Added By</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Updated By</th>
<th style="width:100x;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Ajax:
<script>
// first, put this at the top of your JS code.
let dateParams = {}
// update this with setting dataParams
$('#demo').daterangepicker({
"timePicker": true,
"timePicker24Hour": true,
"startDate": "06/05/2021",
"endDate": "06/06/2021",
locale: {
format: 'M/DD/YYYY hh:mm A'
}
}, function(start, end, label) {
// set the dateParam obj
dateParams = {
start: start.format('YYYY-MM-DD hh:mm'),
end: end.format('YYYY-MM-DD hh:mm')
}
console.log('New date range selected: ' + start.format('YYYY-MM-DD hh:mm') + ' to ' + end.format('YYYY-MM-DD hh:mm') + ' (predefined range: ' + start + + end +')');
});
$(document).ready(function() {
//datatables
table = $('#table_account').DataTable({
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('profile/ajax_list')?>",
"type": "POST",
"data": function (dateParams) {
return $.extend( { "start": dateParams.start,
"end": dateParams.end,}, dateParams, {
});
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
setInterval( function () {
table.ajax.reload(null,false);
}, 1000);
</script>
Controller:
public function ajax_list()
{
$list = $this->profiles->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->firstname;
$row[] = $person->lastname;
$row[] = $person->username;
$row[] = $person->email;
$row[] = $person->mobile;
$row[] = $person->role;
$row[] = $person->status;
$row[] = $person->addedBy;
$row[] = $person->dateCreated;
$row[] = $person->updatedBy;
$row[] = $person->dateUpdated;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person('."'".$person->userID."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->profiles->count_all(),
"recordsFiltered" => $this->profiles->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
Model:
var $table = 'users';
var $column_order = array(null,'userID','firstname','lastname','username','email','mobile','addedBy','dateCreated');
var $order = array('userID' => 'desc');
var $column_search = array('email','firstname','lastname','username','email','mobile','dateCreated');
//set column field database for datatable orderable //set column field database for datatable searchable just firstname , lastname , address are searchable var $order = array('id' => 'desc'); // default order
private function _get_datatables_query()
{
if($this->input->post('daterange')){
$this->db->where('dateCreated >=', $this->input->post('start'));
$this->db->where('dateCreated <=', $this->input->post('end'));
}
// $this->input->post('start'); // YYYY-mm-dd
// $this->input->post('end'); // YYYY-mm-dd
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
To connect the calendar with the data output table, edit your daterangepicker initialization:
// first, put this at the top of your JS code.
let dateParams = {}
// update this with setting dataParams
$('#demo').daterangepicker({
"timePicker": true,
"timePicker24Hour": true,
"startDate": "06/05/2021",
"endDate": "06/06/2021",
locale: {
format: 'M/DD hh:mm A'
}
}, function(start, end, label) {
// set the dateParam obj
dataParams = {
start: start.format('YYYY-MM-DD'),
end: end.format('YYYY-MM-DD')
}
// reload the table
table.ajax.reload();
//console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
});
Over in your DataTable() setup change your ajax to pass the start and end dates
"ajax": {
"url": "<?php echo site_url('profile/ajax_list')?>",
"type": "POST",
"data": function ( d ) {
// add this
return $.extend( {}, d, {
"start": dataParams.start,
"end": dataParams.end
});
// could also be written: return $.extend( {}, d, dataParams);
}
}
Finally, you'll need to pick this up in your CI app so you can search you DB.
$this->input->post('start'); // YYYY-mm-dd
$this->input->post('end'); // YYYY-mm-dd
Then this is just a nit. Please move <table id="table_account" class="table table-bordered table-hover" cellspacing="0"> to right above the first <thead>. Right now there is the datepicker element in between them. Might not matter, but it should be fixed.
https://datatables.net/reference/option/ajax

sortable grid with knockout with ajax load

I am loading an observable array via ajax, hooking up to a table and then adding sorting to the column headers. It works but only sorts random rows. If I bypass the ajax feed and manually declare the observable array, all works well. Am I missing something obvious here?
//The Page
$(document).ready(function () {
var pageModel = function () {
var self = this;
//Variables and observables
self.loading = ko.observable(false);
self.searchQuery = ko.observable("");
self.searchCelebrantId = ko.observable(-1);
//Models used in page
self.celebrantsInstance = ko.observable(new celebrantsModel());
self.marriagesInstance = ko.observable(new marriagesModel());
//var celebrantsInstance = new celebrantsModel();
//var marriageInstance = new singleMarriageModel(1);
//Get data
self.loadData = function () {
return $.when(
self.celebrantsInstance().loadData()
//, self.marriagesInstance().loadData()
);
}
}
var pageInstance = new pageModel({});
pageInstance.loadData()
.done(function () {
setTimeout(function () {
ko.applyBindings(pageInstance);
/* Bootstrap select */
$("select").selectpicker();
$("select").addClass('show-menu-arrow').selectpicker('setStyle');
}, 500);
});
});
//The knockout .js model file
function marriage(data) {
var self = this;
self.id = ko.observable(data.Id);
self.CelebrantId = ko.observable(data.CelebrantId);
self.MarriageDate = ko.observable(data.MarriageDate);
self.MarriagePlace = ko.observable(data.MarriagePlace);
self.WifeFirstName = ko.observable(data.WifeFirstName);
self.WifeMaidenName = ko.observable(data.WifeMaidenName);
self.HusbandFirstName = ko.observable(data.HusbandFirstName);
self.HusbandSurname = ko.observable(data.HusbandSurname);
self.MarriageCertificateNumberToRegistrar = ko.observable(data.MarriageCertificateNumberToRegistrar);
self.MarriageCertificateNumberToCouple = ko.observable(data.MarriageCertificateNumberToCouple);
}
function GetMarriageList(searchQuery) {
return $.ajax("/Marriage/GetMarriageList?searchQuery=" + searchQuery, {
type: "get"
});
};
function GetMarriage(id) {
return $.ajax("/Marriage/GetMarriage?id=" + id, {
type: "get"
});
};
var marriagesModel = function () {
var self = this;
self.loading = ko.observable(false);
self.searchQuery = ko.observable("a");
self.searchCelebrantId = ko.observable(-1);
self.marriages = ko.observableArray([]);
self.sortCommand = ko.observable("MarriagePlace asc");
self.headers = [
// { title: 'Marriage Date', sortPropertyName: 'MarriageDate', asc: true },
{ title: 'Marriage Place', sortPropertyName: 'MarriagePlace', asc: true },
{ title: 'Wife First Name', sortPropertyName: 'WifeFirstName', asc: true },
{ title: 'Wife Maiden Name', sortPropertyName: 'WifeMaidenName', asc: true },
{ title: 'Husband First Name', sortPropertyName: 'HusbandFirstName', asc: true },
{ title: 'Husband Surname', sortPropertyName: 'HusbandSurname', asc: true },
{ title: ' Marriage Certificate\nTo Registrar', sortPropertyName: 'MarriageCertificateNumberToRegistrar', asc: true },
{ title: 'Marriage Certificate \nTo Couple', sortPropertyName: 'MarriageCertificateNumberToCouple', asc: true },
{ title: '' },
];
self.activeSort = self.headers[0]; //set the default sort
self.sort = function (header, event) {
//if this header was just clicked a second time
if (self.activeSort === header) {
header.asc = !header.asc; //toggle the direction of the sort
} else {
self.activeSort = header; //first click, remember it
}
var prop = self.activeSort.sortPropertyName;
var ascSort = function (a, b) { return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
var descSort = function (a, b) { return a[prop] > b[prop] ? -1 : a[prop] < b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
var sortFunc = self.activeSort.asc ? ascSort : descSort;
self.marriages.sort(sortFunc);
};
self.loadData = function () {
self.loading(true);
return GetMarriageList(self.searchQuery())
.done(function (data) {
var mappedMarriages = $.map(data, function (item) {
return new marriage(item);
});
self.marriages(mappedMarriages);
self.loading(false);
});
}
return GetMarriageList(self.searchQuery())
.done(function (data) {
var mappedMarriages = $.map(data, function (item) {
return new marriage(item);
});
self.marriages(mappedMarriages);
self.loading(false);
});
}
//HTML Table
<table id="event-table" class="table table-striped" style="width: 100%; display: none" data-bind="visible: (!loading() && marriages().length > 0)">
<tr data-bind="foreach: headers">
<th data-bind="click: sort, text: title"></th>
</tr>
<!-- ko foreach: marriages -->
<tr>
<!--<td style="width: 120px"><span data-bind='html: moment(MarriageDate()).format("DD/MM/YYYY")'></span></td>-->
<td><span data-bind='html: MarriagePlace'></span></td>
<td><span data-bind='html: WifeFirstName'></span></td>
<td><span data-bind='html: WifeMaidenName'></span></td>
<td><span data-bind='html: HusbandFirstName'></span></td>
<td><span data-bind='html: HusbandSurname'></span></td>
<td><span data-bind='html: MarriageCertificateNumberToRegistrar'></span></td>
<td><span data-bind='html: MarriageCertificateNumberToCouple'></span></td>
<td><a data-bind='attr: { "href": "/Marriage/Edit/" + id }'>Edit</a></td>
</tr>
<!-- /ko -->
</table>
You might want to have a look at knockout-transformations.
Cheers

Showing a loader widget on AngularJs sort feature using orderBy

I need to show a loader widget on AngularJs sort feature using orderBy.
I have around 10 options for sorting for ex. By Name, By price etc. On my page I load around 100 objects due to which, the sorting takes a little time to reflect. Hence I need to show a loader widget during this interval.
Basically, once I click the required option(ie. By Name, By price etc.), the loader widget would show and once the sorting is done, the loader goes away and the page renders.
It would be even great if someone could please modify the below fiddle with this change.
http://www.jsfiddle.net/vjF2D/
function ContactListCtrl($scope){
$scope.sortorder = 'surname';
$scope.contacts =
[
{ "name":"Richard", "surname":"Stallman", "telephone":"1234 98765" },
{ "name":"Linus", "surname":"Torvalds", "telephone":"2345 87654" },
{ "name":"Donald", "surname":"Knuth", "telephone":"3456 76543" }
];
}
------------------------------------------
<div ng-app ng-controller="ContactListCtrl">
<h1>AngularJS Sorting Example</h1>
<select ng-model="sortorder">
<option value="surname">Surname (A-Z)</option>
<option value="-surname">Surname (Z-A)</option>
</select>
<table class="contacts">
<tr>
<th>Name</th>
<th>Telephone</th>
</tr>
<tr ng-repeat="contact in contacts | orderBy:sortorder">
<td ng-class-even="'even'">{{contact.name}}, {{contact.surname}}</td>
<td ng-class-even="'even'">{{contact.telephone}}</td>
</tr>
</table>
</div>
Thanks in advance !!!
I suggest you angularjs-spinner, see GitHub sources
Or:
HTML
<div ng-controller="ContactListCtrl">
<h1>AngularJS Sorting Example</h1>
<select ng-model="sortorder">
<option value="surname">Surname (A-Z)</option>
<option value="-surname">Surname (Z-A)</option>
</select>
<table class="contacts">
<tr>
<th>Name</th>
<th>Telephone</th>
</tr>
<tr ng-repeat="contact in contacts | orderBy:sortorder" repeat-done="layoutDone()" >
<td ng-class-even="'even'">{{contact.name}}, {{contact.surname}}</td>
<td ng-class-even="'even'">{{contact.telephone}}</td>
</tr>
</table>
<div id="veil" ng-show="isLoading"></div>
<div id="feedLoading" ng-show="isLoading">Loading...</div>
</div>
JS
var app = angular.module('myModule', []);
app.controller('ContactListCtrl', function ($scope) {
$scope.sortorder = 'surname';
$scope.contacts = [{
"name": "Richard",
"surname": "Stallman",
"telephone": "1234 98765"
}, {
"name": "Linus",
"surname": "Torvalds",
"telephone": "2345 87654"
}, {
"name": "Donald",
"surname": "Knuth",
"telephone": "3456 76543"
}];
$scope.setLoading = function (loading) {
$scope.isLoading = loading;
}
$scope.layoutDone = function () {
console.log("vvvvv");
$scope.setLoading(false);
}
$scope.loadFeed = function(url) {
$scope.setLoading(true);
}
$scope.loadFeed();
});
app.directive('repeatDone', function() {
return function(scope, element, attrs) {
if (scope.$last) { // all are rendered
scope.$eval(attrs.repeatDone);
}
}
})
The edited Demo Fiddle
Thanks to Maxim Shoustin for solving my queries. Kudos to him for providing the below working jsfiddle example :
http://www.jsfiddle.net/vjF2D/11
var app = angular.module('myModule', []);
app.controller('ContactListCtrl', function ($scope, $timeout, $filter) {
var sortingOrder = 'name';
$scope.sortingOrder = sortingOrder;
$scope.sortorder = 'surname';
$scope.contacts = [{
"name": "Richard",
"surname": "Stallman",
"telephone": "1234 98765"
}, {
"name": "Donald",
"surname": "Knuth",
"telephone": "3456 76543"
}, {
"name": "Linus",
"surname": "Torvalds",
"telephone": "2345 87654"
}];
$scope.setLoading = function (loading) {
$scope.isLoading = loading;
}
$scope.layoutDone = function (value) {
console.log(value);
$scope.setLoading(true);
$timeout(function() {
// take care of the sorting order
if ($scope.sortingOrder !== '') {
if(value == 'surname'){
$scope.contacts = $filter('orderBy')($scope.contacts, $scope.sortingOrder, false);
}
else if(value == '-surname'){
$scope.contacts = $filter('orderBy')($scope.contacts, $scope.sortingOrder, true);
}
else{
$scope.contacts = $filter('orderBy')($scope.contacts, $scope.sortingOrder, false);
}
}
$scope.setLoading(false);
}, 1000);
}
$scope.loadFeed = function(url) {
$scope.setLoading(true);
}
$scope.loadFeed();
});
app.directive('repeatDone', function() {
return function(scope, element, attrs) {
if (scope.$last) { // all are rendered
scope.$eval(attrs.repeatDone);
}
}
})

Reusable Client Side/Ajax enabled Table Design ( Don't use default Asp.Net Grid )

I am looking for code to have below features with HTML table.
Design a reusable grid which has the below default features:
Ajax enabled Table ( No Post backs)
Paging through Ajax Calls
Sorting through Ajax calls
Filtering through Ajax calls
You can use jQuery datatables.net for this task.You can download js file from here
download JS file
here i am going to explain a sample for the same.i have used entity framework to fetch the data from back-end.if you are not using entity framework then get the concept from this sample and implement it on your way.
HTML:
<table id="tblList" cellpadding="0" cellspacing="0" border="0" class="grid" >
<thead>
<tr>
<th class="headingtextcenter">#</th><th class="headingtextcenter">Name</th><th class="headingtextcenter">Description</th>
<th class="headingtextcenter">Form Publish Date</th><th class="headingtextcenter">Last Data Entery Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="Scripts/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(window).load(function () {
var oTable = $('#tblList').dataTable({
"bServerSide": true,
"sAjaxSource": "List.aspx?load=1",
"bProcessing": true,
"sPaginationType": "full_numbers",
"oLanguage": { "sZeroRecords": "<div style='width:99%;text-align:center;padding:4px;'>No record found.</div>" },
"aoColumns": [
{ "sName": "ID","bSortable": false },
{ "fnRender": function (oObj) {
return '<a href=\"Whitepaper/' +
oObj.aData[3] + '\" >' + oObj.aData[0] + '</a>';
},"bSortable": false },
{ "sName": "Description", "bSortable": false},
{ "sName": "FormPublishDate", "bSortable": false},
{ "sName": "LastDataEnteryDate"}
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$('td', nRow).addClass("cells");
}
});
});
</script>
//User fnRowCallback function if you want to add css to all td
Code Behind(List.aspx.cs):
private FormEntities objEntities;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["load"] != null && Request.QueryString["load"].ToString() == "1")
BindData();
}
}
private void BindData()
{
using (objEntities = new FormEntities())
{
//For sorting
Func<Forms, string> orderingFunction = (c => c.LastDataEnteryDate);
var sortDirection = Request["sSortDir_0"];
IEnumerable<Forms> allForms = objEntities.Forms;
var sSearch = Convert.ToString(Request["sSearch"]);
if (!string.IsNullOrEmpty(sSearch))
{
allVideoLibraries = allForms.Where(c => c.LastDataEnteryDate.ToLower().Contains(sSearch.ToLower()));
}
if (sortDirection == "asc")
allForms = allForms.OrderBy(orderingFunction);
else if (sortDirection == "desc")
allForms = allForms.OrderByDescending(orderingFunction);
var displayForms = allForms.Skip(int.Parse(Request.QueryString["iDisplayStart"])).Take(int.Parse(Request.QueryString["iDisplayLength"]));
var result = from v in displayForms
select new[] { v.ID,v.Name, v.Description, v.FormPublishDate ,v.LastDataEnteryDate };
JavaScriptSerializer toJSON = new JavaScriptSerializer(); //need to add reference using System.Web.Script.Serialization;
Response.Clear();
string datastring = toJSON.Serialize(new
{
sEcho = Request.QueryString["sEcho"],
iTotalRecords = result.Count(),
iTotalDisplayRecords = result.Count(),
aaData = result
});
Response.Write(datastring);
Response.End();
}
}

Resources