Adding text to an Angular Ui-Grid date column - angular-ui-grid

I have an angular ui-grid that has a column for a date, which indicates the date an email was sent to a new user:
{
name: "SentOn",
displayName: "Sent On",
cellFilter: "date:\"yyyy-MM-dd HH:mm\""
}
The email is not sent until a number of background processes are complete, so this date can be null. When the date is null, nothing shows in the cell.
Is there a straight forward way to display some default text when the date is null?

There are two ways you can achieve what you want here.
You can provide a custom template for the cell to handle the null date scenario. This is probably easier option too.
{
name: "SentOn",
displayName: "Sent On",
cellTemplate : "<div class=\"ui-grid-cell-contents\">{{COL_FIELD CUSTOM_FILTERS || \"Not Sent\"}}</div>"
}
Or you can create a custom cellFilter which will take care of the null date. You can extend the existing date filter to achieve this.
var app = angular.module('app', ['ngTouch', 'ui.grid','ui.grid.edit']);
var grid;
app.filter('customDate', function($filter){
var standardDateFilterFn = $filter('date');
return function(dateToFormat){
if(!dateToFormat)
return "Not Sent Yet";
return standardDateFilterFn(dateToFormat, 'yyyyMMddhhmmss');
}
});
app.controller('MainCtrl', ['$scope', function ($scope) {
var myData = [
{
id1:new Date(),id2:"2",id3:"3",id4:"4",id5:"5",
}, {
id1:null,id2:"2",id3:"3",id4:"4",id5:"5",
},]
var getTemplate = function()
{
return "<div class=\"ui-grid-cell-contents\">{{COL_FIELD CUSTOM_FILTERS}}</div>";
}
var cellEditable = function($scope){
if($scope.row.entity.oldId4===undefined)
return false;
return $scope.row.entity.oldId4!=$scope.row.entity.id4;
}
$scope.gridOptions = {
enableFiltering: true,
onRegisterApi: function(gridApi){
grid = gridApi;
},
data: myData,
columnDefs:[
{
field: 'id1',
displayName: "id1",
width: 200,
cellTemplate: getTemplate(),
cellFilter : "customDate:\"yyyy-MM-dd HH:mm\""
},
{
field: 'id2',
displayName: "id2",
width: 100
},{
field: 'id3',
displayName: "id3",
width: 100
},{
field: 'id4',
displayName: "id4",
width: 100
},{
field: 'id5',
displayName: "id5",
width: 100
},
],
}
$scope.gridOptions.onRegisterApi = function(gridApi){
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.edit.on.afterCellEdit($scope,function(rowEntity, colDef, newValue, oldValue){
rowEntity.oldId4 = oldValue;
$scope.$apply();
});
};
$scope.test = function()
{
window.alert("Cell clicked")
}
}]);
here is a working plnkr. http://plnkr.co/edit/qHaRzkzxGEphuTMQ6oqG?p=preview

Related

ui-grid columnDefs : how to translate cell content to some value which is user-friendly and a function of the data?

I have this ==>
$scope.uiGrid306 = {
rowTemplate:rowtpl,
columnDefs: [{
field: '_ab_area', name: 'Area', width: "7%"
, filter: { type: uiGridConstants.filter.SELECT, selectOptions: AREAS }
}, { ...
}, {
field: '_ab_x_style', name: 'Groups', width: "5%"
, filter: { type: uiGridConstants.filter.SELECT, selectOptions: RISKS, condition: uiGridConstants.filter.EXACT
}
}
]//columnDefs
, enableFiltering: true
};//-->gridOptions
But my _ab_x_style has the data which is not user-friendly as I have wanted them to be. So I need a function to return a translation of those data to user-friendly words. The problem is HOW???
For that purpose, you need to apply a cellFilter to the cell content. And a translate function to drop down options which also has those non-userfriendly data.
cellFilter is a filter to apply to the content of each cell.
$scope.uiGrid306 = {
rowTemplate:rowtpl,
columnDefs: [{
field: '_ab_area', name: 'Area', width: "7%"
, filter: { type: uiGridConstants.filter.SELECT, selectOptions: AREAS }
}, { ...
}, {
field: '_ab_x_style', name: 'Groups', width: "5%", cellFilter: 'TranslateMe'
, filter: { type: uiGridConstants.filter.SELECT, selectOptions: RISKS, condition: uiGridConstants.filter.EXACT
}
}
]//columnDefs
, enableFiltering: true
};//-->gridOptions
Right after your angular controller, you implement that filter by
Yours.controller('BodyController', function($scope, $http, $filter, uiGridConstants, $timeout, $resource) {
})
.filter( 'TranslateMe', function (){
return(function(value){
return((value=='dataExcep'?'red':(value=='dataExcepLblueNoVal'?'blue':(value=='dataExcepYellowRevHi'?'yellow':(value=='dataExcepNew'?'aqua':'neutral')))));
});
});
Then, for your drop-down options, you also have to apply a function
function TranslateMe(value){
return((value=='dataExcep'?'red':(value=='dataExcepLblueNoVal'?'blue':(value=='dataExcepYellowRevHi'?'yellow':'neutral'))));
}
for your options building as such
function loadOptions( $scope, serverdata ){
_.forEach( _.sortBy( _.uniq( _.pluck( serverdata, '_ab_x_style' )) ), function ( eachOpt ) {
RISKS.push( { value: eachOpt, label: TranslateMe(eachOpt) } )
} );
$scope.uiGrid306.columnDefs[10].filter.selectOptions = RISKS;
}
Result (instead of user unfriendly data, I have the names of the colors) --

filter the ui grid value based on the row check box is selected

This is the ui grid code( minimal)
//js file
vm.gridOptions1 = {
enableColumnResizing: true,
enableAutoResizing: false,
columnDefs: [
{
field: 'createdDate',
displayName: 'Created Date',
type: 'date',
cellFilter: 'date:"dd-MM-yyyy"',
enableHiding: false, headerTooltip: 'Created Date'
},{
name: 'Refer',
displayName: 'Refer', enableSorting: false, headerTooltip: 'Refer',
cellTemplate: '<input type="checkbox" ng-model="row.entity.isReferred" />'
}
]});
On click of this byutton I need to filter, get only rows which check box is selected(isReferred = true)
//html file
<button type="button" class="btn btn-primary-joli " ng-click="srchctrl.send">Send</button>
This is the file trying to get the filtered list based on the redeffered check box value, but its not working.
//JS file
vm.send = function () {
if (vm.gridApi.selection.data != null && vm.gridApi.selection.data != undefined) {
vm.referredList = filterFilter(vm.gridApi.selection.data, {
isReferred: true
});
console.log("referredList :"+JSON.stringify(referredList));
}
};
How can I get all the value ticked. I don't want to invoke method on each click event on check box.
I think the easiest way to achieve this is by using the gridApi.grid.registerRowsProcessor function. I have adapted a Plunker to show what I mean:
http://plnkr.co/edit/lyXcb90yQ0ErUJnSH7yF
Apps.js:
var app = angular.module('plunker', ['ui.grid']);
app.controller('MainCtrl', ['$scope', 'uiGridConstants', function($scope, uiGridConstants) {
$scope.gridOptions = {
columnDefs: [
{field: 'col1', displayName: 'Column 1', width: 175},
{field: 'col2', displayName: 'isReferred', width: '*'}
],
data: [
{ col1: "Hello 1",col2: true},
{ col1: "Hello 2", col2: false},
{ col1: "Hello 3", col2: true},
{ col1: "Hello 4", col2: false},
{ col1: "Hello 5", col2: true}
],
enableFiltering: true,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
$scope.Filter = Filter;
$scope.ShowAll = ShowAll;
function ShowAll() {
$scope.gridApi.grid.removeRowsProcessor(myFilter);
$scope.gridApi.core.queueGridRefresh();
}
function Filter() {
$scope.gridApi.grid.registerRowsProcessor(myFilter, 150);
$scope.gridApi.core.queueGridRefresh();
}
function myFilter(renderableRows) {
renderableRows.forEach( function(row) {
row.visible = row.entity.col2;
});
return renderableRows;
}
}]);
Clicking the Filter button will register the myFilter RowsProcessor, which will iterate through all rows to alter the visible attribute.
Clicking the ShowAll button will remove the RowsProcessor, thus showing all previously hidden rows again.
Whenever an isReferred value changes, the filter will cause the grid to automatically update this change.

Change angular ui-grid's columns visibility

I want to show/hide columns after the grid is rendered. Before i moved to the new ui-grid
I called to toggleVisible() but now it doesn't seem to work.
I tried to change the column def visibility(or any other property) like bellow
columnDefs[9].visible = false;
When I set the visibility on the column definition(before render) it does work, but after wards i cannot change it.
Old question, but this works for me in 3.0.0-rc.20. I'm guessing columnDefs needs to be in scope.
$scope.columnDefs = [
{ name: 'one' },
{ name: 'two', visible: false }
];
$scope.grid = {
data: 'data',
columnDefs: $scope.columnDefs
};
$scope.grid.onRegisterApi = function(gridApi){
$scope.gridApi = gridApi;
};
$scope.showColumnTwo = function() {
$scope.columnDefs[1].visible = true;
$scope.gridApi.grid.refresh();
};
Just started working with angular-ui-grid so this might be not the best solution.
Try including the uiGrid api object and then invoking the refersh method on a grid object
...
$scope.gridOptions.onRegisterApi = function(gridApi){
$scope.gridApi = gridApi;
};
....
columnDefs[9].visible = false;
$scope.gridApi.grid.refresh();
In case anyone was looking for a solution that didn't require you to create a columndDef.
s.gridOptions = {
data: 'myData',
onRegisterApi: function(gridApi) {
gridApi.core.registerColumnsProcessor(hideIdColumn);
s.gridApi = gridApi;
function hideIdColumn(columns){
columns.forEach(function(column){
if(column.field==='_id'){
column.visible=false;
}
});
return columns;
}
}
Just replace the column.field==='_id' part with your own condition.
Also don't forget to return the columns or you will not get any columns at all.
The answer from user3310980 was preferred when I saw it but there is very little documentation on the registerColumnsProcessor method. I found reference to his comment about using it without column definitions so I wanted to make it clear that you can certainly use this method with column defs. This provides for some interesting flexibility.
In this example, there are four columns that swap with four other columns determined by a toggle button. $ctrl.showDetails is true when sales columns should display and false when payment items should display.
In the column definitions, the onRefresh property is defined as a method to call for the column on grid refresh and the setVisibleColumns method is supplied to registerColumnsProcessor(). When the grid is refreshed, for each column, it will check the column definition in the colDef property and call the onRefresh method for each column that defines it, with this set to the column object.
/*--------------------------------------------*/
/* showPayments - Make payment items visible. */
/* showDetails - Make sales items visible. */
/*--------------------------------------------*/
var showPayments = function() { this.visible = !$ctrl.showDetails; };
var showDetails = function() { this.visible = $ctrl.showDetails; };
var columnDefs =
[
{ field: 'receiptDate', displayName: 'Date', width: 120, type: 'date', cellFilter: "date:'MM/dd/yyyy'", filterCellFiltered: true },
{ field: 'receiptNumber', displayName: 'Rcpt No', width: 60, type: 'number' },
{ field: 'receiptFrom', displayName: 'From', width: 185, type: 'string' },
{ field: 'paymentMethod', displayName: 'Method', width: 60, type: 'string', onRefresh: showPayments },
{ field: 'checkNumber', displayName: 'No', width: 60, type: 'string', onRefresh: showPayments },
{ field: 'checkName', displayName: 'Name', width: 185, type: 'string', onRefresh: showPayments },
{ field: 'paymentAmount', displayName: 'Amount', width: 70, type: 'string', onRefresh: showPayments },
{ field: 'description', displayName: 'Desc', width: 100, type: 'string', onRefresh: showDetails },
{ field: 'accountNumber', displayName: 'Acct No', width: 80, type: 'string', onRefresh: showDetails },
{ field: 'accountName', displayName: 'Acct Name', width: 160, type: 'string', onRefresh: showDetails },
{ field: 'salesTotal', displayName: 'Amount', width: 70, type: 'string', onRefresh: showDetails }
];
/*----------------------------------------------------*/
/* Columns processor method called on grid refresh to */
/* call onRefresh' method for each column if defined. */
/*----------------------------------------------------*/
var setVisibleColumns = function(cols)
{
for (var i=0; i < cols.length; i++)
if (cols[i].colDef.onRefresh)
cols[i].colDef.onRefresh.call(cols[i]);
return cols;
};
/*----------------------------------*/
/* Callback to set grid API in */
/* scope and add columns processor. */
/*----------------------------------*/
var onRegisterApi = function(api)
{
$ctrl.itemList.api = api;
api.core.registerColumnsProcessor(setVisibleColumns);
};
/*------------------------------*/
/* Configure receipt item grid. */
/*------------------------------*/
$ctrl.showDetails = false;
$ctrl.itemList =
{
columnDefs: columnDefs,
enableCellEdit: false,
enableColumnMenus: false,
enableFiltering: false,
enableHorizontalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED,
enableVerticalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED,
data: [],
onRegisterApi: onRegisterApi
};
When $ctrl.showDetails is changed, a simple refresh will swap the columns.
$ctrl.showDetails = !$ctrl.showDetails;
$ctrl.itemList.api.grid.refresh();
I hope this is helpful to someone.

Export data from jqxgrid

I want to export all data in my jqxgrid into json and send it to another page via AJAX.
My problem is when I click export button, the data in the grid and data before export was not the same. It change float number to Interger. Here is my code:
Javascript:
$('#export_bt').on('click', function(){
var row = $("#jqxgrid").jqxGrid('exportdata', 'json');
$('#debug').html(row);
console.log(row);
});
var tableDatas = [
{"timestamp":"06:00:00","A":99.49,"B":337.77,"C":155.98},
{"timestamp":"07:00:00","A":455.67,"B":474.1,"C":751.68},
{"timestamp":"08:00:00","A":1071.02,"B":598.14,"C":890.47}
];
var tableDatafields = [
{"name":"timestamp","type":"string"},
{"name":"A","type":"number"},
{"name":"B","type":"number"},
{"name":"C","type":"number"}
];
var tableColumns = [
{"text":"Times","datafield":"timestamp","editable":"false","align":"center","cellsalign":"center","width":150},
{"text":"A","datafield":"A","editable":"false","align":"center"},
{"text":"B","datafield":"B","editable":"false","align":"center"},
{"text":"C","datafield":"C","editable":"false","align":"center"}
];
function setTableData(table_data,table_column,table_datafields)
{
sourceTable.localdata = table_data;
sourceTable.datafields = table_datafields;
dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
$("#jqxgrid").jqxGrid({columns:table_column});
$("#jqxgrid").jqxGrid('updatebounddata');
$('#jqxgrid').jqxGrid('sortby', 'timestamp', 'asc');
$("#jqxgrid").jqxGrid('autoresizecolumns');
for(var i=0;i<table_column.length;i++){
$('#jqxgrid').jqxGrid('setcolumnproperty',table_column[i].datafield,'cellsrenderer',cellsrenderer);
}
}
var cellsrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
if (value||value===0) {
return value;
}
else {
return '-';
}
};
var sourceTable ={ localdata: '', datatype: 'array'};
var dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
dataAdapterTable.dataBind();
$("#jqxgrid").jqxGrid({
width: '500',
autoheight:true,
source: dataAdapterTable,
sortable: true,
columnsresize: false,
selectionmode: 'none',
columns: [{ text: '', datafield: 'timestamp', width:'100%' , editable: false, align:'center'}]
});
setTableData(tableDatas,tableColumns,tableDatafields);
Html:
<div id="jqxgrid"></div>
<button id="export_bt">Export</button>
<div id="debug"></div>
http://jsfiddle.net/jedipalm/jHE7k/1/
You can add the data type in your source object as below.
datafields: [{ "name": "timestamp", "type": "number" }]
And also I suggest you to apply cellsformat in your column definition.
{ text: 'timestamp', datafield: 'timestamp', cellsalign: 'right', cellsformat: 'd' }
The possible formats can be seen here.
Hope that helps
You can export data in very fast way just like it is id jqxGrid with
var rows = $("#jqxGrid").jqxGrid("getrows");
It will be json array.

jqGrid parameters. Can't be passed

I call web-service to fill jqGrid and wants to pass parameters to it
I use the following code (client side):
jQuery('#EmployeeTable').jqGrid({
datatype: function () {
var params = new Object();
params.page = 10;
params.Filter = true;
params.DateStart = null;
params.DateEnd = null;
params.TagID = null;
params.CategoryID = 3;
params.StatusID = 1;
params.IsDescription = true;
$.ajax({
url: '/Admin/IdeasJSON',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#EmployeeTable")[0];
grid.addJSONData(data);
}
},
error: function () {
alert("Error with AJAX callback");
}
});
},
also, there is propotype of web-method (MVC):
public JsonResult IdeasJSON(int? page, bool? Filter, DateTime? DateStart, DateTime? DateEnd, int? TagID, int? CategoryID, int? StatusID, bool? IsDescription)
Why all these parameters are null?
[ADDED 04/11]
jQuery(document).ready(function () {
var StatusID = null, Filter = null, page = null, DateStart = null, DateEnd = null, TagID = null, CategoryID = null, IsDescription = null;
if (jQuery.url.param('StatusID') != null) {
StatusID = jQuery.url.param('StatusID');
}
if (jQuery.url.param('Filter') != null) {
Filter = jQuery.url.param('Filter');
}
if (jQuery.url.param('page') != null) {
page = jQuery.url.param('page');
}
if (jQuery.url.param('DateStart') != null) {
DateStart = jQuery.url.param('DateStart');
}
if (jQuery.url.param('DateEnd') != null) {
DateEnd = jQuery.url.param('DateEnd');
}
if (jQuery.url.param('TagID') != null) {
TagID = jQuery.url.param('TagID');
}
if (jQuery.url.param('CategoryID') != null) {
CategoryID = jQuery.url.param('CategoryID');
}
if (jQuery.url.param('IsDescription') != null) {
IsDescription = jQuery.url.param('IsDescription');
}
jQuery('#EmployeeTable').jqGrid({
url: '/Admin/IdeasJSON',
datatype: 'json',
postData: { page: page, Filter: Filter, DateStart: DateStart, DateEnd: DateEnd, TagID: TagID, StatusID: StatusID, CategoryID: CategoryID, IsDescription: IsDescription },
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Logged By', 'Logging Agency (ID)', 'Title', 'Status', 'Points', 'Categories', 'Created Date', 'Description', 'Jira ID#', 'Portal Name', '', '', '', '', '', '', ''],
colModel: [
{ name: 'LoggedBy', width: 100 },
{ name: 'LoggingAgencyID', width: 85 },
{ name: 'Title', width: 100 },
{ name: 'Status', width: 100 },
{ name: 'Points', width: 40, align: 'center' },
{ name: 'Categories', width: 100 },
{ name: 'CreatedDate', width: 80, formatter: ndateFormatter },
{ name: 'Description', width: 300 },
{ name: 'JiraID', width: 55 },
{ name: 'PortalName', width: 100 },
{ name: 'IdeaID', width: 25, formatter: ActionDescriptionFormatter },
{ name: 'IdeaID', width: 25, formatter: ActionEditFormatter },
{ name: 'IdeaID', width: 25, formatter: ActionDeleteFormatter },
{ name: 'IdeaGridCommentsAndSubideas', width: 25, formatter: ActionIdeaGridCommentsAndSubideas },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridCountVotes },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridLinkIdeas },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridIdeaType },
],
pager: '#EmployeeTablePager',
width: 1000,
viewrecords: true,
caption: 'Idea List',
excel: true
}).jqGrid('navGrid', '#EmployeeTablePager', {
add: false,
edit: false,
del: false,
search: false,
refresh: false
}).jqGrid('navButtonAdd', '#EmployeeTablePager', {
caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: ReturnExcel,
position: "last"
}).jqGrid('navButtonAdd', '#EmployeeTablePager', {
caption: " Export to CSV ",
buttonicon: "ui-icon-bookmark",
onClickButton: ReturnCSV,
position: "last"
});
});
You should not use datatype as the function to use the JSON data. Probably you used template of very old examples.
For example in the "UPDATED" part of the answer you could find full demo project which demonstrate how to use jqGrid in ASP.MVC 2.0 inclusive paging, sorting and filtering/advanced searching.
If you want post some additional parameters to the server as a part of jqGrid request you should use postData parameters in the form postData: {CategoryID: 3, StatusID: 1, IsDescription:true, Filter: true}

Resources