I have the code with showing data from json file, but i need update table single row data to the database. In my code I can update only angulajs table. So i need one more thing, need to update that one mysql also. hence, i need to know how data will pass mysql to using js& PHP, the code is given below.
Script.js
var app = angular.module('app',
[
'ui.grid',
'ui.grid.pagination',
'ui.grid.selection',
'ui.grid.cellNav',
'ui.grid.expandable',
'ui.grid.edit',
'ui.grid.rowEdit',
'ui.grid.saveState',
'ui.grid.resizeColumns',
'ui.grid.pinning',
'ui.grid.moveColumns',
'ui.grid.exporter',
'ui.grid.infiniteScroll',
'ui.grid.importer',
'ui.grid.grouping'
]);
app.filter('genderFilter', function () {
var genderHash = {
'M': 'male',
'F': 'female'
};
app.gridApi.core.on.rowsRendered(scope,() => {
if (!gridApi.grid.expandable.expandedAll && !initialized)
{
gridApi.expandable.expandAllRows();
initialized = true;
}
});
return function (input) {
var result;
var match;
if (!input) {
return '';
} else if (result = genderHash[input]) {
return result;
} else if ((match = input.match(/(.+)( \([$\d,.]+\))/)) && (result = genderHash[match[1]])) {
return result + match[2];
} else {
return input;
}
};
});
app.filter('maritalFilter', function () {
var genderHash = {
'M': 'Married',
'S': 'Single'
};
return function (input) {
var result;
var match;
if (!input) {
return '';
} else if (result = genderHash[input]) {
return result;
} else if ((match = input.match(/(.+)( \([$\d,.]+\))/)) && (result = genderHash[match[1]])) {
return result + match[2];
} else {
return input;
}
};
})
app.controller('gridCtrl', ['$scope', '$http', '$log', '$timeout', 'uiGridConstants', '$q', '$interval',
function ($scope, $http, $log, $timeout, uiGridConstants, $q, $interval) {
$scope.gridOptions = {
enableRowSelection: true,
enableSelectAll: true,
selectionRowHeaderWidth: 35,
rowHeight: 35,
showGridFooter: true
};
$scope.convertDate = function (str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("/");
};
var expandableScope = {};
$scope.gridOptions = {
enableFiltering:true,
expandableRowTemplate: '<div style="padding:5px;"><div ui-grid="row.entity.subGridOptions[0]" ui-grid-edit ui-grid-row-edit ui-grid-selection style="height:340px;display:inline-block;"></div></div>',
expandableRowHeight: 350,
columnDefs: [
{ name: 'Project', enableCellEdit: true, },
/* {
name: "",
field:"fake",
cellTemplate: '<div class="ui-grid-cell-contents" >' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Delete</button>' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Edit</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.saveEdit($event)">Update</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.cancelEdit($event)">Cancel</button>' +
'</div>',
enableCellEdit: false,
enableFiltering:false,
enableSorting: false,
showSortMenu : false,
enableColumnMenu: false,
}*/
/*{ name: 'managerid', enableCellEdit: true },
//{
// name: 'hiredate', enableCellEdit: true, type: "date", cellFilter: 'date:"yyyy/MM/dd"',
// cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.convertDate(row.entity[col.field])}}</div>'
//},
{
name: 'title', enableCellEdit: true,
cellTemplate: '<div class="ui-grid-cell-contents"><div ng-class="{\'viewr-dirty\' : row.inlineEdit.entity[col.field].isValueChanged }">{{row.entity[col.field]}}</div></div>'
},
// { name: 'birthdate', enableCellEdit: true, type: "date", cellFilter: 'date:"yyyy/MM/dd"' },
{
name: 'maritalstatus', enableCellEdit: true, cellFilter: "maritalFilter",
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownValueLabel: 'maritalstatus',
editDropdownOptionsArray: [
{ id: 'M', maritalstatus: 'Married' },
{ id: 'S', maritalstatus: 'Single' }]
},
{
name: 'gender', enableCellEdit: true, cellFilter: 'genderFilter',
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownValueLabel: 'gender',
editDropdownOptionsArray: [
{ id: 'M', gender: 'male' },
{ id: 'F', gender: 'female' }]
},*/
],
enableGridMenu: true,
virtualizationThreshold: 60,
expandableRowScope: {
subGridVariable: 'subGridScopeVariable'
}
}
//$scope.gridOptions.multiSelect = true;
$http.get('https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/data/employeeData.json')
.success(function (data) {
$scope.gridOptions.data = data.slice(0, 55);; //[data[0], data[1]];
});
$scope.info = {};
$scope.gridOptions.onRegisterApi = function (gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
var msg = 'row selected ' + row.isSelected;
$log.log(msg);
});
gridApi.selection.on.rowSelectionChangedBatch($scope, function (rows) {
var msg = 'rows changed ' + rows.length;
$log.log(msg);
});
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
var selectedRows = $scope.gridApi.selection.getSelectedRows();
if (newValue != oldValue) {
rowEntity.state = "Changed";
//Get column
var rowCol = $scope.gridApi.cellNav.getFocusedCell().col.colDef.name;
angular.forEach(selectedRows, function (item) {
item[rowCol] = rowEntity[rowCol];// $scope.convertDate(rowEntity[rowCol]);
item.state = "Changed";
item.isDirty = false;
item.isError = false;
});
}
});
gridApi.rowEdit.on.saveRow($scope, function (rowEntity) {
// create a fake promise - normally you'd use the promise returned by $http or $resource
//Get all selected rows
var selectedRows = $scope.gridApi.selection.getSelectedRows();
//var rowCol = $scope.gridApi.cellNav.getFocusedCell().col.colDef.name;
var promise = $q.defer();
$scope.gridApi.rowEdit.setSavePromise(rowEntity, promise.promise);
$interval(function () {
if (rowEntity.gender === 'male') {
promise.reject();
} else {
promise.resolve();
}
}, 3000, 1);
})
gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
if (row.isExpanded) {
row.entity.subGridOptions =[{
virtualizationThreshold: 60,
enableFiltering:true,
// expandableRowTemplate: '<div style="padding:5px;"><div ui-grid="row.entity.subGridOptions[0]" ui-grid-edit ui-grid-row-edit ui-grid-selection style="height:340px;display:inline-block;"></div></div>',
//expandableRowHeight: 350,
columnDefs: [
{ name: 'firstname', enableCellEdit: true, width: 100},
{ name: 'Activity Description', width: 500 },
{ name: 'Start' },
{ name: 'Department' },
{ name: 'Remarks' },
{
name: "",
field:"fake",
cellTemplate: '<div class="ui-grid-cell-contents" >' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Delete</button>' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Edit</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.saveEdit($event)">Update</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.cancelEdit($event)">Cancel</button>' +
'</div>',
enableCellEdit: false,
enableFiltering:false,
enableSorting: false,
showSortMenu : false,
enableColumnMenu: false,
}
],
onRegisterApi: function (gridApi) {
$scope.text = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
console.log(row);
});
gridApi.rowEdit.on.saveRow($scope, function (rowEntity) {
// create a fake promise - normally you'd use the promise returned by $http or $resource
//Get all selected rows
var selectedRows = $scope.text.selection.getSelectedRows();
//var rowCol = $scope.gridApi.cellNav.getFocusedCell().col.colDef.name;
var promise = $q.defer();
$scope.text.rowEdit.setSavePromise(rowEntity, promise.promise);
$interval(function () {
if (rowEntity.gender === 'male') {
promise.reject();
} else {
promise.resolve();
}
}, 3000, 1);
})
}
}],
$http.get('https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/data/employeeContact.json')
.success(function (data) {
row.entity.subGridOptions[0].data = data.slice(0, 45);
});
}
});
};
}]);
angular.module('ui.grid').factory('InlineEdit', ['$interval', '$rootScope', 'uiGridRowEditService',
function ($interval, $rootScope, uiGridRowEditService) {
function inlineEdit(entity, index, grid) {
this.grid = grid;
this.index = index;
this.entity = {};
this.isEditModeOn = false;
this.init(entity);
}
inlineEdit.prototype = {
init: function (rawEntity) {
var self = this;
for (var prop in rawEntity) {
self.entity[prop] = {
value: rawEntity[prop],
isValueChanged: false,
isSave: false,
isCancel: false,
isEdit: false
}
}
},
enterEditMode: function (event) {
event && event.stopPropagation();
var self = this;
self.isEditModeOn = true;
// cancel all rows which are in edit mode
self.grid.rows.forEach(function (row) {
if (row.inlineEdit && row.inlineEdit.isEditModeOn && row.uid !== self.grid.rows[self.index].uid) {
row.inlineEdit.cancelEdit();
}
});
// Reset all the values
for (var prop in self.entity) {
self.entity[prop].isSave = false;
self.entity[prop].isCancel = false;
self.entity[prop].isEdit = true;
}
},
saveEdit: function (event) {
event && event.stopPropagation();
var self = this;
self.isEditModeOn = false;
for (var prop in self.entity) {
self.entity[prop].isSave = true;
self.entity[prop].isEdit = false;
}
uiGridRowEditService.saveRow(self.grid, self.grid.rows[self.index])();
},
cancelEdit: function (event) {
event && event.stopPropagation();
var self = this;
self.isEditModeOn = false;
for (var prop in self.entity) {
self.entity[prop].isCancel = true;
self.entity[prop].isEdit = false;
}
}
}
return inlineEdit;
}]);
index.html
<html>
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/Css/ui-grid.css" />
<script src="https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/Js/vendor/angular.js"></script>
<script src="https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/Js/vendor/ui-grid.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" class="">
<div class="" ng-controller="gridCtrl">
<div ui-grid="gridOptions" ui-grid-move-columns="" ui-grid-edit="" ui-grid-row-edit="" ui-grid-selection="" ui-grid-expandable="" class="grid" style="height:800px"></div>
</div>
</body>
</html>
Thanks Advance
Related
I want to build project team-wise portfolio items
project -1
- Feature -1
- Feature -2
project - 2
- Feature -1
- Feature -2
I am unable to get project and features as children in rally tree builder, I have tried like below:
Rally.onReady(function() {
Ext.define('Rally.example.SimpleTreeGrid', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
Ext.create('Rally.data.wsapi.TreeStoreBuilder').build({
models: ['PortfolioItem/Feature'],
autoLoad: true,
enableHierarchy: true
}).then({
success: this._onStoreBuilt,
scope: this
});
},
_onStoreBuilt: function(store) {
this.add({
xtype: 'rallytreegrid',
store: store,
context: this.getContext(),
enableEditing: false,
enableBulkEdit: false,
shouldShowRowActionsColumn: false,
enableRanking: false,
childEls: ["title"],
columnCfgs: [
'Name',
'State',
'Owner'
]
});
}
});
Rally.launchApp('Rally.example.SimpleTreeGrid', {
name: 'Simple Tree Grid Example'
});
});
Got it..! I have taken grouped by grid as reference and built the grid
_createGrid: function ()
{
var filter = Ext.create('Rally.data.wsapi.Filter', { property: 'Release.Name', operator: '=', value: ReleaseBoxValue });
if (!this.down('#storygrid'))
{
this.grid = this.add({
xtype: 'rallygrid',
itemId: 'storygrid',
columnCfgs: [
{
text: 'Formatted ID', dataIndex: 'FormattedID', xtype: 'templatecolumn',
tpl: Ext.create('Rally.ui.renderer.template.FormattedIDTemplate')
},
{
text: 'Name', dataIndex: 'Name'
},
{
text: 'Accepted', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(acceptedStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'Completed', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(completedPercentage, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'Defined', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(definedStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'Grooming', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(grommedStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'In-Progress', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(inProgressStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'Grand Total', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(totalStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'Optum Accepted Stories', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(acceptedStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
},
{
text: 'Stories yet to be accepted', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(completedPercentage, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
}
,
{
text: 'Total Stories', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var userStoriesCount = 0;
_.each(totalStories, function (record)
{
if (record.key == Release)
{
userStoriesCount++;
}
}, this);
html = '<span>' + userStoriesCount + '</span>';
return html;
}
}
,
{
text: 'Optum Accepted Stories (%)', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var accepetedCount = 0;
_.each(acceptedStories, function (record)
{
if (record.key == Release)
{
accepetedCount++;
}
}, this);
var totalStoriesCount = 0;
_.each(totalStories, function (record)
{
if (record.key == Release)
{
totalStoriesCount++;
}
}, this);
var decTotal = accepetedCount / totalStoriesCount;
if (!isNaN(decTotal))
{
html = '<span>' + Math.round((decTotal) * 100) + '%</span>';
}
else
{
html = '<span>0%</span>';
}
return html;
}
}
,
{
text: 'Stories yet to be accepted (%)', dataIndex: 'FormattedID',
renderer: function (value)
{
var Release = value;
var html = "";
var completedCount = 0;
_.each(completedPercentage, function (record)
{
if (record.key == Release)
{
completedCount++;
}
}, this);
var totalStoriesCount = 0;
_.each(totalStories, function (record)
{
if (record.key == Release)
{
totalStoriesCount++;
}
}, this);
var decTotal = completedCount / totalStoriesCount;
if (!isNaN(decTotal))
{
html = '<span>' + Math.round((decTotal) * 100) + '%</span>';
}
else
{
html = '<span>0%</span>';
}
return html;
}
}
],
context: this.getContext(),
features: [{
ftype: 'groupingsummary',
groupHeaderTpl: '{name} ({rows.length})'
}
],
filters: [filter],
storeConfig: {
model: 'portfolioitem/feature',
groupField: 'Name',
groupDir: 'ASC',
fetch: ['FormattedID', 'Name', 'Release', 'Project', 'UserStories', 'HierarchicalRequirement'],
filters: [filter],
getGroupString: function (record)
{
var owner = record.get('Project');
return (owner && owner._refObjectName) || 'No Name';
}
}
});
}
else
{
var filter = Ext.create('Rally.data.wsapi.Filter', { property: 'Release.Name', operator: '=', value: ReleaseBoxValue });
var treeGrid = this.down('rallygrid'),
treeStore = treeGrid.getStore();
treeStore.clearFilter(true);
treeStore.filter(filter);
}
}
var nameTemplate = ""
function templateFunction() {
if ($scope.useBindScript === true) {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "file"></div>';
} else {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "text"></div>';
}
return nameTemplate;
}
$scope.gridOptionsArg = {
enableRowSelection: true,
enableRowHeaderSelection: false,
enableCellEditOnFocus: true,
data: $scope.arginputFiles,
columnDefs: [{
name: 'mark',
cellTemplate: templateFunction()
},
{
name: 'argument',
field: 'index',
enableCellEdit: false
},
{
name: 'value',
field: 'value'
}
]
};
$scope.addRow = function() {
if (condition) {
$scope.gridOptionsArg.data.push({
"argument": "Application",
"value": ""
});
$scope.columns[$scope.columns.length - 2].cellTemplate = templateFunction();
}
}
This is the definition of my grid. Once I click on some button add row function would be called where I want to add a row to the grid with new cellTemplate. Everytime it is returning a textbox.
I have created a plunker with your needs: http://plnkr.co/edit/GKmcwZurGSf6VXjC2gu0?p=preview
The following function creates a new row and add it to the ui-grid data:
vm.addRow = function() {
vm.gridOptions1.data.unshift({"name":"Test", "gender":"Male", "company":"test"});
vm.grid1Api.core.notifyDataChange( uiGridConstants.dataChange.EDIT );
};
I have used the same function to return the template:
function templateFunction() {
var nameTemplate;
if (useBindScript === true) {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "file"></div>';
} else {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "text"></div>';
}
return nameTemplate;
}
I have a UI-grid which display few details in First Column beacon column I need to display count of all beacons along with Beacon(count) in header-text. this count m getting in response from a service.
This is my JS file
define([
'angular',
'./module',
'moment',
'select2'
], function(angular, module, moment, select2) {
'use strict';
module.controller('eventViewerSelectPanelController', [
'$scope',
'$translate',
'messageBus',
'toasty',
'$filter',
'$rootScope',
'$q',
'facilityDetails',
'logger',
'$interval',
'filterStateService',
'deviceStateService',
'$timeout',
'sensoryEventService',
'scarletConsoleConfigService',
function($scope, $translate, messageBus, toasty, $filter, $rootScope, $q, facilityDetails, logger, $interval, filterStateService, deviceStateService, $timeout, sensoryEventService, scarletConsoleConfigService) {
var macRegex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i;
$scope.numberOfRecords = -1;
filterStateService.resetFilter();
var timestampColSortFun = function(a, b, rowA, rowB, direction){
console.log(a, b, rowA, rowB, direction);
return 1
}
$scope.loadSensoryEvents = function() {
var query = filterStateService.getSearchQuery().trim();
var deviceType = filterStateService.getActiveFilterState().toUpperCase();
var macListQuery = query.split(',');
var macList = [];
var errorMsg = '';
for(var item of macListQuery){
if(item != ''){
if(item.search(macRegex) > -1){
macList.push(item);
} else {
errorMsg = 'MAC not in valid format';
break;
}
}
}
if(errorMsg === '' && macList.length < 1){
errorMsg = 'Field is required.';
}
if(errorMsg === '' && macList.length > scarletConsoleConfigService.getConfig().eventMacMaxCount){
errorMsg = 'MAC entered exceeds the max allowed count.'
}
if(errorMsg != ''){
messageBus.send(Message.FilterPanelValidationFailed, errorMsg);
return;
}
$scope.processing = true;
console.log('duration', $scope.duration);
var eventPromise = sensoryEventService.load(query, deviceType,$scope.duration);
eventPromise.then(function(response) {
console.log(response)
var dataLength = response.sensoryEvents.length;
$scope.numberOfRecords = dataLength;
if(dataLength > 0){
$scope.gridOptions.data = processTimestamp(response.sensoryEvents);
**// Here m getting the count in response**
$scope.count = response.beaconCount;
console.log("value of count is=====",$scope.count);
$scope.receiverCount = response.receiverCount;
messageBus.send(Message.NumberOfSearchRecordsChanged, dataLength);
}
$scope.processing = false;
}, function(error) {
$scope.processing = false;
console.error('error getting events');
toasty.serviceError(error);
});
}
$scope.gridOptions = {
rowHeight: 60,
multiSelect: false,
enableColumnMenus: false,
enableEdit: false,
enableSoring: true,
enableHorizontalScrollbar: 0,
columnDefs: [{
name: 'beacon',
****// Here M adding count to display Name****
displayName:'Beacon(' +$scope.count + ')',
width: '25%',
cellTemplate: 'beacon-template'
},
{
name: 'receiver',
width: '25%',
headerCellTemplate: 'receiver-header-template',
cellTemplate: 'receiver-template'
},
{
name: 'storageTimestamp',
width: '30%',
displayName: 'Timestamps',
cellTemplate: 'timestamp-template'
// sortingAlgorithm: timestampColSortFun
},
{
name: 'rssi',
width: '7%',
displayName: 'RSSI',
cellTemplate: 'rssi-template'
},
{
name: 'beaconMajor',
width: '13%',
displayName:'Major/Minor',
cellTemplate:'major-minor-template'
}
]
};
$scope.select2DurationSettings = {
placeholder: 'Select',
width: '125px',
border: 'none',
minimumResultsForSearch: 10
};
// Initialize select2 functionality after page loads
$timeout(function() {
$('#selectDuration').select2($scope.select2DurationSettings);
}, 0);
$scope.durations = [
{
key: 'label.duration.5',
valueFrom: 0,
valueTo: 5
},
{
key: 'label.duration.15',
valueFrom: 0,
valueTo: 15
},
{
key: 'label.duration.30',
valueFrom: 0,
valueTo: 30
},
{
key: 'label.duration.60',
valueFrom: 0,
valueTo: 60
},
{
key: 'lable.duration.last.1-2',
valueFrom: 60,
valueTo: 120
},
{
key: 'lable.duration.last.2-3',
valueFrom: 120,
valueTo: 180
},
{
key: 'lable.duration.last.3-4',
valueFrom: 180,
valueTo: 240
}
];
$scope.duration = JSON.stringify($scope.durations[0]);
function processTimestamp(items) {
items.forEach(function(item, index) {
item.timestampUI = moment(item.storageTimestamp).format('L');
item.deviceTimestampUI = moment(item.deviceTimestamp).format('HH:mm:ss:SSS');
item.gatewayTimestampUI = moment(item.gatewayTimestamp).format('HH:mm:ss:SSS');
item.storageTimestampUI = moment(item.storageTimestamp).format('HH:mm:ss:SSS');
});
return items;
}
$scope.$onMessage(Message.SubmitFilterForm, function(event) {
$scope.loadSensoryEvents();
});
$(window).resize(function() {
$scope.getTableHeight();
});
$scope.getTableHeight = function() {
var height = $(window).height() - 160;
return {
height: (height) + "px"
};
};
}
]);
});
I have attached both screenshots actual and expected second one is expected one count is coming as undefined. Hoe can i get the count. Please reply Thanks.
The issue is grid is loading before the data is coming from response. How to resolve it?
I'm working with ui-grid and server-side filtering. For each column I send a request to API with param based on filter value. By default param is empty
var filterOptions = {
filterBy: '&$filter=',
filterParam: ""
};
// and api call looks like
?$orderby=id-&pageSize=250&pageNbr=1&$filter=
if I setup any filter I send next request
param: filterOptions.filterParam = 'eventTypeId==' + evtTypeId
request: ?$orderby=id-&pageSize=250&pageNbr=1&$filter=eventTypeId==2
So what I want is pretty simple idea, I want to check if filter is already applied and send a request like
?$orderby=id-&pageSize=250&pageNbr=1&$filter=eventTypeId==2,studyId==1
but unfortunately I cannot catch any applied filters. I appreciate if somebody could help with my issue.
My code below
columnDef
$scope.gridOptions.columnDefs = [
{
field: 'title',
cellClass: getCellClass,
useExternalFiltering: true
}, {
field: 'description',
cellClass: getCellClass,
enableFiltering: true,
useExternalFiltering: true
}, {
displayName: 'Type',
field: 'eventType.name',
filter: {
selectOptions: $scope.eventType,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Study Name',
field: 'study.name',
filter: {
selectOptions: $scope.study,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Priority',
field: 'priority.name',
filter: {
selectOptions: $scope.priority,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Severity',
field: 'severity.name',
filter: {
selectOptions: $scope.severity,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Status',
field: 'status.name',
filter: {
selectOptions: $scope.status,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Created',
field: 'occuredDate',
width: '12%',
filterHeaderTemplate: '<div class="row ui-grid-filter-container">' +
'<div ng-repeat="colFilter in col.filters" class="col-md-6 col-sm-6 col-xs-6">' +
'<div custom-grid-date-filter-header></div></div></div>',
filters: [
{
name: 'From',
condition: uiGridConstants.filter.GREATER_THAN_OR_EQUAL
},
{
name: 'To',
condition: uiGridConstants.filter.LESS_THAN_OR_EQUAL
}
],
cellFilter: 'date:"dd MMMM yyyy, h:mm:ss a"',
cellClass: getCellClass,
useExternalFiltering: false
}, {
displayName: 'Modified', field: 'createdDate',
width: '12%',
filterHeaderTemplate: '<div class="row ui-grid-filter-container">' +
'<div ng-repeat="colFilter in col.filters" class="col-md-6 col-sm-6 col-xs-6">' +
'<div custom-grid-date-filter-header></div></div></div>',
filters: [
{
name: 'From',
condition: uiGridConstants.filter.GREATER_THAN_OR_EQUAL
},
{
name: 'To',
condition: uiGridConstants.filter.LESS_THAN_OR_EQUAL
}
],
cellFilter: 'date:"dd MMMM yyyy, h:mm:ss a"',
cellClass: getCellClass,
useExternalFiltering: false
}
];
RegisterApi
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
gridApi.selection.selectRow($scope.gridOptions.data[0]);
gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
paginationOptions.pageNbr = '&pageNbr=' + newPage ;
paginationOptions.pageSize = '&pageSize=' + pageSize;
getData();
});
gridApi.core.on.filterChanged( $scope, function() {
var grid = this.grid;
// Define behavior for cancel filtering
$scope.isfilterclear = true;
angular.forEach(grid.columns, function( col ) {
if(col.filters[0].term){
$scope.isfilterclear = false;
}
});
if($scope.isfilterclear) {
$timeout(function() {
$rootScope.refresh()
},500);
}
// Filter behavior
$scope.textFilter = grid.columns[1].filters[0].term;
if($scope.textFilter) {
$scope.$watch('textFilter', function (newVal, oldVal) {
filterOptions.filterParam = 'title==*' + newVal + "*";
}, true);
getData()
}
$scope.desFilter = grid.columns[2].filters[0].term;
if($scope.desFilter) {
$scope.$watch('desFilter', function (newVal, oldVal) {
filterOptions.filterParam = 'description==*' + newVal + "*";
}, true);
getData()
}
for (var et = 0; et < $scope.eventType.length; et ++){
var evtType = $scope.eventType[et].name;
var evtTypeId = $scope.eventType[et].id;
filterOptions.filterParam = 'eventTypeId==' + evtTypeId;
if( grid.columns[3].filters[0].term === evtType ) {
getData()
}
}
for (var stud = 0; stud < $scope.study.length; stud ++){
var study = $scope.study[stud].name;
var studyId = $scope.study[stud].id;
filterOptions.filterParam = 'studyId==' + studyId;
if( grid.columns[4].filters[0].term === study ) {
getData()
}
}
for (var pr = 0; pr < $scope.priority.length; pr ++){
var priority = $scope.priority[pr].name;
var priorityId = $scope.priority[pr].id;
filterOptions.filterParam = 'priorityId==' + priorityId;
if( grid.columns[5].filters[0].term === priority ) {
getData()
}
}
for (var sev = 0; sev < $scope.severity.length; sev ++){
var severity = $scope.severity[sev].name;
var severityId = $scope.severity[sev].id;
filterOptions.filterParam = 'severityId==' + severityId;
if( grid.columns[6].filters[0].term === severity ) {
getData()
}
}
for (var stat = 0; stat < $scope.status.length; stat ++){
var status = $scope.status[stat].name;
var statusId = $scope.status[stat].id;
filterOptions.filterParam = 'statusId==' + statusId;
if( grid.columns[7].filters[0].term === status ) {
getData()
}
}
});
Where getData() is
var getData = function () {
eventService.getEventsWithParams(
sortOptions.orderBy,
sortOptions.directions,
paginationOptions.pageSize,
paginationOptions.pageNbr,
filterOptions.filterBy,
filterOptions.filterParam
)
.then(function (data) {
$scope.gridOptions.data = data;
// ***
angular.forEach($scope.gridOptions.data, function (val) {
val.occuredDate = new Date(val.occuredDate);
});
// $interval whilst we wait for the grid to digest the data we just gave it
$interval(function () {
$scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
}, 0, 1);
});
};
my plunker
(unfortunately I cannot provide the real API, but hope it will help anyhow)
The working code is
gridApi.core.on.filterChanged( $scope, function() {
// Declare vars
var grid = this.grid;
var columns = grid.columns;
$scope.columnTitle = grid.columns[1].filters[0].term;
$scope.columnDesc = grid.columns[2].filters[0].term;
var columnType = grid.columns[3].filters[0].term;
var columnStudy = grid.columns[4].filters[0].term;
var columnPriority = grid.columns[5].filters[0].term;
var columnSeverity = grid.columns[6].filters[0].term;
var columnStatus = grid.columns[7].filters[0].term;
var columnCreatedDate = grid.columns[8].filters[0].term;
var columnModifiedDate = grid.columns[9].filters[0].term;
// Create request for selectable filters
var query = [];
var string;
function request (id, param) {
if(param === "title==" || param === "description=="){
query.push(param + "*" + id + "*")
} else {
query.push(param + id);
}
if (query.length <= 1){
return query
} else {
string = query.join(";");
return string;
}
}
// Define behavior for cancel filtering
$scope.isfilterclear = true;
angular.forEach(columns, function( col ) {
if(col.filters[0].term){
$scope.isfilterclear = false;
}
});
if($scope.isfilterclear) {
$timeout(function() {
$rootScope.refresh()
},500);
}
// Filter behavior for columns
if($scope.columnTitle) {
$scope.$watch('columnTitle', function (newVal, oldVal) {
filterOptions.filterParam = request(newVal, 'title==*');
}, true);
getData()
}
if($scope.columnDesc) {
$scope.$watch('columnDesc', function (newVal, oldVal) {
filterOptions.filterParam = request(newVal, 'description==');
}, true);
getData()
}
if(columnType) {
filterOptions.filterParam = request(columnType, 'eventTypeId==');
getData();
}
if(columnStudy) {
filterOptions.filterParam = request(columnStudy, 'studyId==');
getData();
}
if(columnPriority) {
filterOptions.filterParam = request(columnPriority, 'priorityId==');
getData();
}
if(columnSeverity) {
filterOptions.filterParam = request(columnSeverity, 'severityId==');
getData();
}
if(columnStatus) {
filterOptions.filterParam = request(columnStatus, 'statusId==');
getData();
}
if(columnCreatedDate){
filterOptions.filterParam = request($rootScope.setFilterDate, 'occuredDate>=');
getData()
}
if(columnModifiedDate){
filterOptions.filterParam = request($rootScope.setFilterDate, 'occuredDate>=');
getData()
}
});
As you can see, I declared custom function with two params where I'm providing my request param for each call, I'm not sure about elegancy of this way but for two week I didn't find better solution
I have a ng-grid when I add a record into that the row gets inserted at the bottom of the grid, I want to display the newly added row in the top of my grid so that a user would be able to know which data is added.
here is my app.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope, $http) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: true
};
$scope.totalServerItems = 0;
$scope.pagingOptions = {
pageSizes: [5, 10, 20],
pageSize: 5,
currentPage: 1
};
$scope.setPagingData = function(data, page, pageSize){
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.myData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('largeLoad.json').success(function (largeLoad) {
data = largeLoad.filter(function(item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data,page,pageSize);
});
} else {
$http.get('largeLoad.json').success(function (largeLoad) {
$scope.setPagingData(largeLoad,page,pageSize);
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.edit = function (row) {
row.entity.edit = !row.entity.edit;
};
$scope.gridOptions = {
data: 'myData',
enableRowSelection: true,
showGroupPanel: true,
enableCellSelection: false,
jqueryUIDraggable: true,
enablePaging: true,
showFooter: true,
totalServerItems:'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions,
columnDefs: [{
field: 'nm',
displayName: 'Name',
cellTemplate: '<div class="ngCellText"><div ng-show="!row.entity.edit">{{row.getProperty(col.field)}}</div>' +
'<div ng-show="row.entity.edit" class="ngCellText"><input type="text" ng-model="row.entity.nm"/></div></div>'
},
{
field: 'cty',
displayName: 'city',
cellTemplate: '<div class="ngCellText"><div ng-show="!row.entity.edit">{{row.getProperty(col.field)}}</div>' +
'<div ng-show="row.entity.edit" class="ngCellText"><input type="text" ng-model="row.entity.cty"/></div></div>'
},
{
field: 'hse',
displayName: 'Address',
cellTemplate: '<div class="ngCellText"><div ng-show="!row.entity.edit">{{row.getProperty(col.field)}}</div>' +
'<div ng-show="row.entity.edit" class="ngCellText"><input type="text" ng-model="row.entity.hse"/></div></div>'
},
{
field: 'yrs',
displayName: 'PinCode',
cellTemplate: '<div class="ngCellText"><div ng-show="!row.entity.edit">{{row.getProperty(col.field)}}</div>' +
'<div ng-show="row.entity.edit" class="ngCellText"><input type="text" ng-model="row.entity.yrs"/></div></div>'
},
{
displayName: 'Edit',
cellTemplate: '<button id="editBtn" type="button" class="btn btn-primary" ng-click="edit(row)" >Modify</button> '
},
{
displayName: 'Remove',
cellTemplate: '<button id="removebtn" type="button" class="btn btn-primary" ng-click="removeRow($index)" >Remove</button> '
}
]
};
$scope.removeRow = function() {
var index = this.row.rowIndex;
$scope.gridOptions.selectItem(index, false);
$scope.myData.splice(index, 1);
};
This is my addRow function; when this function gets executed a row gets inserted at the bottom of the grid I want that this new row to be displayed at the top most whenever the add button is clicked
$scope.addRow = function() {
$scope.myData.push({nm: 'abc', cty: 0 , hse:'abcd' , yrs:2014});
};
});
here is my code on plunker:
http://plnkr.co/edit/QbsQ6uDgNxts9TUMERj2?p=info
When you push data into an array, javascript will always put it at the end. A possible solution would be to use unshift in stead of push:
The unshift() method adds new items to the beginning of an array, and
returns the new length.