Hi when i click on a button my ag-grid loads the data from database.Next time how to see the data in ag-grid without clicking on a button.Basically i want to save and restore the state of ag-grid to avoid the button click every time in order to load the data in ag-grid.
agGrid.initialiseAgGridWithAngular1(angular);
var module = angular.module("example", ["agGrid"]);
module.controller("exampleCtrl", function($scope, $http) {
var columnDefs = [
{headerName: "Athlete", field: "athlete", width: 150, cellRenderer: athleteCellRendererFunc},
{headerName: "Age", field: "age", width: 90, cellRenderer: ageCellRendererFunc},
{headerName: "Country", field: "country", width: 120, cellRenderer: countryCellRendererFunc},
{headerName: "Year", field: "year", width: 90},
{headerName: "Date", field: "date", width: 110},
{headerName: "Sport", field: "sport", width: 110},
{headerName: "Gold", field: "gold", width: 100},
{headerName: "Silver", field: "silver", width: 100},
{headerName: "Bronze", field: "bronze", width: 100},
{headerName: "Total", field: "total", width: 100}
];
$scope.gridOptions = {
columnDefs: columnDefs,
rowData: null,
angularCompileRows: true
};
function ageClicked(age) {
window.alert("Age clicked: " + age);
}
function athleteCellRendererFunc() {
return '<span ng-bind="data.athlete"></span>';
}
function ageCellRendererFunc(params) {
params.$scope.ageClicked = ageClicked;
return '<button ng-click="ageClicked(data.age)" ng-bind="data.age"></button>';
}
function countryCellRendererFunc(params) {
return '<country name="'+params.value+'"></country>';
}
$scope.getData = function(){
//console.log("hello");
$http.get("https://raw.githubusercontent.com/ag-grid/ag-grid-docs/master/src/olympicWinners.json")
.then(function(res){
$scope.gridOptions.api.setRowData(res.data);
});
}
});
module.directive('country', function () {
var FLAG_CODES = {
'Ireland': 'ie',
'United States': 'us',
'Russia': 'ru',
'Australia': 'au',
'Canada': 'ca',
'Norway': 'no',
'China': 'cn',
'Zimbabwe': 'zw',
'Netherlands': 'nl',
'South Korea': 'kr',
'Croatia': 'hr',
'France': 'fr'
};
var flagHtml = '<img ng-show="flagCode" class="flag" border="0" width="20" height="15" src="https://flags.fmcdn.net/data/flags/mini/{{flagCode}}.png" />';
var nameHtml = '<span ng-bind="countryName" />';
return {
scope: true,
template: flagHtml + ' ' + nameHtml,
link: function(scope, element, attrs) {
var countryName = attrs.name;
scope.countryName = countryName;
scope.flagCode = FLAG_CODES[countryName];
}
};
});
Below is the plunker code link:
https://plnkr.co/edit/PKTiFpd9WM1UeELT72ht?p=preview`
Are you trying to retrieve the data as soon as the grid has been initialized? If so, you can use the onGridReady event:
// create and inject a factory, e.g. "gridStateFactory"
$scope.gridOptions = {
columnDefs: columnDefs,
rowData: null,
angularCompileRows: true,
onGridReady: function() {
if (gridStateFactory.isInitialized) {
$scope.getData();
}
};
$scope.getData = function(){
//console.log("hello");
$http.get("https://raw.githubusercontent.com/ag-grid/ag-grid-
docs/master/src/olympicWinners.json")
.then(function(res){
gridStateFactory.setInitialized();
$scope.gridOptions.api.setRowData(res.data);
});
}
Related
I am using ag-grid to display the values from database.Using cellRendering to check for conditions if there is no data i should display No Data else with data.
But i see only blank when there is data.How to bind the data to the grid if there is data.
var columnDefs = [
{headerName: "Athlete", field: "athlete", width: 150, cellRenderer: athleteCellRendererFunc},
{headerName: "Age", field: "age", width: 90},
];
$scope.gridOptions = {
columnDefs: columnDefs,
rowData: null,
angularCompileRows: true
};
function athleteCellRendererFunc(row) {
if(row.data.athlete == null)
{
return '<span ng-bind="data.athlete">No Data</span>';
}
else
{
return '<span ng-bind="data.athlete"></span>';
}
}
Use below code
return '<span>' + data.athlete + '</span>';
cellRenderer simply expects the final HTML template to be returned.
I want to hide columns in ui-grid if there is no data present in that column. Like here the column "Issued By" and "Issued On" should be hidden as there is no data present.
HTML
<body ng-app="appHome">
<div ng-controller="ctrlRequestDetail">
<div class="gridStyle" ui-grid="gridInvUsage">
</div>
</div>
</body>
Controller.js
var myApp = angular.module('appHome', ['ui.grid']);
myApp.controller("ctrlRequestDetail", ['$scope', 'MetadataOrgFactory', function ($scope, MetadataOrgFactory) {
MetadataOrgFactory.getIdApiCall('geteventinvlist', $scope.reqDetailData.EventId, function (dataSuccess) {
//Web API call to Fetch Data
$scope.invUsageData = dataSuccess;
}, function (dataError) {
});
$scope.gridInvUsage = {
data: 'invUsageData',
columnDefs: [
{ field: 'InvBookStartTime', displayName: 'Book Start Time', cellFilter: 'date:"dd-MM-yyyy HH:mm"' },
{ field: 'InvBookEndTime', displayName: 'Book End Time', cellFilter: 'date:"dd-MM-yyyy HH:mm"' },
{ field: 'SourceInvNumber', displayName: 'Source Inventory' },
{ field: 'BookingRemarks', displayName: 'Booking Remarks' },
{ field: 'BookingStatus', displayName: 'Booking Status' },
{ field: 'AcceptRejectBy', displayName: 'Accept/Reject By' },
{ field: 'IssuedBy', displayName: 'Issued By' },
{ field: 'IssuedOnTime', displayName: 'Issued On' },
]
}
}])
How to achieve this functionality?
You could easily toggle the particular column visible property to show and hide the based on arrived data from API.
Code
$scope.columns = [
{ field: 'InvBookStartTime', displayName: 'Book Start Time', cellFilter: 'date:"dd-MM-yyyy HH:mm"' },
{ field: 'InvBookEndTime', displayName: 'Book End Time', cellFilter: 'date:"dd-MM-yyyy HH:mm"' },
{ field: 'SourceInvNumber', displayName: 'Source Inventory' },
{ field: 'BookingRemarks', displayName: 'Booking Remarks' },
{ field: 'BookingStatus', displayName: 'Booking Status' },
{ field: 'AcceptRejectBy', displayName: 'Accept/Reject By' },
{ field: 'IssuedBy', displayName: 'Issued By' },
{ field: 'IssuedOnTime', displayName: 'Issued On' },
];
$scope.gridOptions = {
data: 'invUsageData',
columnDefs: $scope.columns,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
//Once data arrives, inside ajax success
//Web API call to Fetch Data
$scope.invUsageData = dataSuccess;
$scope.columns.forEach(function(col){
col.visible = $scope.invUsageData.filter(function(item){
return angular.isDefined(item[col. field]);
}).length;
});
Plunker Demo
Retrieve column definition via ajax and after updating columnDefs property refresh the grid to see the changes
function getColumns() {
$http.get('columns.json').then(function(response) {
$scope.columns = response.data;
$scope.gridOptions.columnDefs = $scope.columns;
$scope.columns.forEach(function(col) {
col.visible = $scope.invUsageData.filter(function(item) {
return angular.isDefined(item[col.field]);
}).length;
});
//updated grid after colDef changed.
$scope.gridApi.grid.refresh();
});
}
$scope.gridOptions = {
data: 'invUsageData',
columnDefs: $scope.columns,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
Updated Demo
I'm currently trying to read my column footer to make sure that the total sum from the aggregate is exactly 100. However I can not find a way to get that value from the grid functions. Maybe I missed a function in the docs. Is there a way to accomplish this or will I have to manually loop through my grid and sum the values?
You can use aggregates on the column footer to automatically show the sum of all the values in the column.
you can have your grid config like below
$scope.gridOptions = {
showGridFooter: true,
showColumnFooter: true,
enableFiltering: true,
columnDefs: [
{ field: 'name', width: '13%' },
{ field: 'address.street',aggregationType: uiGridConstants.aggregationTypes.sum, width: '13%' },
{ field: 'age', aggregationType: uiGridConstants.aggregationTypes.avg, aggregationHideLabel: true, width: '13%' },
{ name: 'ageMin', field: 'age', aggregationType: uiGridConstants.aggregationTypes.min, width: '13%', displayName: 'Age for min' },
{ name: 'ageMax', field: 'age', aggregationType: uiGridConstants.aggregationTypes.max, width: '13%', displayName: 'Age for max' },
{ name: 'customCellTemplate', field: 'age', width: '14%', footerCellTemplate: '<div class="ui-grid-cell-contents" style="background-color: Red;color: White">custom template</div>' },
{ name: 'registered', field: 'registered', width: '20%', cellFilter: 'date', footerCellFilter: 'date', aggregationType: uiGridConstants.aggregationTypes.max }
],
data: data,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
}
};
http://plnkr.co/edit/nv1eJAIyD5xNDn8XI6L9?p=preview
To get the value from the footer, provided you know the column index and have a reference to the gridApi.
$scope.getFooterValue = function()
{
console.log($scope.gridApi);
alert($scope.gridApi.grid.columns[2].getAggregationValue());
}
I'm using ui-grid with my Cordova application. When I try to populate the ui-grid, sometimes data is displayed on the left like in the picture below:
Any help?
HTML
<div ui-grid="{data: gridOptions, columnDefs: gridColumns, paginationPageSize: 10, enableColumnMenus: false, enableHorizontalScrollbar : 0,
enableVerticalScrollbar : 0}" ui-grid-auto-resize ui-grid-pagination class="grid_transmiss"> </div>
JS
$scope.gridColumns = [{
field: 'ref',
displayName: 'Référence'
}, {
field: 'Emq',
displayName: 'Nombre de plots empilés'
}, {
field: 'charge',
displayName: 'Charge nominale (daN)'
}, {
field: 'fp',
displayName: 'Fréquence propre(Hz)'
}, {
field: 'attenuation',
displayName: 'Atténuation(%)'
}, {
field: 'flechereel',
displayName: 'Flèche réelle statique (mm)'
}, {
name: 'Courbe',
displayName: 'Courbe',
cellTemplate: '<i ng-click="grid.appScope.goToChart()"><img src="img/chart.png" style="width=20px;height:20px" alt="Voir courbe" /></i>'
}];
Try defining your grid in your controller like this:
$scope.gridOptions = {
columnDefs: [
{
field: 'ref', displayName: 'Référence', width: "*"
},
{
field: 'Emq', displayName: 'Nombre de plots empilés', width: "*"
},
{
field: 'charge', width: 110, displayName: 'Charge nominale (daN)'
},
{ field: 'fp', displayName: 'Fréquence propre(Hz)', width: "*"
},
{
field: 'attenuation', displayName: 'Atténuation(%)', width: "*"
},
{
field: 'flechereel', displayName: 'Flèche réelle statique (mm', width: "*"
},
{
field: 'Courbe', displayName: 'Release Courbe', width: "*",
cellTemplate: '<i ng-click="grid.appScope.goToChart()"><img src="img/chart.png" style="width=20px;height:20px" alt="Voir courbe" /></i>'
},
],
showGridFooter: true,
enableFiltering: true,
enableSorting: false,
enableColumnMenus: false,
paginationPageSizes: [100, 120, 140],
paginationPageSize: 100,
enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
enableGridMenu: false,
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
}
};
Then in your HTML:
<div ui-grid="gridOptions" class="grid" ui-grid-pagination ui-grid-exporter ui-grid-auto-resize></div>
Also, make sure you include 'uiGridConstants' in our controller definition like so:
ContractorCtrl.$inject = ['$scope', '$interval', '$window', '$filter', 'uiGridConstants', '$q', '$timeout'];
function ContractorCtrl($scope, $interval, $window, $filter, uiGridConstants, $q, $timeout)
Let me know if this solves your issue.
change your column definition according to below format. It will work.
$scope.gridOptions = {
columnDefs: [
{name:'clumnName', fields: 'DisplayValue', width: '20%'},
{name:'clumnName', fields: 'DisplayValue', width: '20%'},
{name:'clumnName', fields: 'DisplayValue', width: '20%'},
],
data: $scope.DisplayDataSet,
}
I have simple controller:
angular.module('it.works', ['ngResource'])
.controller 'ItWorksCtrl', ($scope, Task) ->
$scope.worksTable = {
data: Task.query(),
columnDefs: [
{ field: "created_at", cellFilter: "date:'dd.MM.yyyy'", displayName: 'Дата создания' },
{ field: "task", cellFilter: "limitTo:300", displayName: 'Описание задачи' },
{ field: "performer", displayName: 'Исполнитель' },
{ field: "task_type", displayName: 'Срочность' },
{ field: "is_orgtechnik_task", displayName: 'Оргтехника', cellTemplate: "<div class='ui-grid-cell-contents'><i class='fa {{ COL_FIELD == true && \"fa-check\" }}'></i></div>" },
{ field: "department", displayName: 'Подразделение' },
{ field: "customer", displayName: 'Заказчик' },
{ field: "customer_telephone", displayName: 'Телефон заказчика' },
{ field: "end_date", displayName: 'Дата окончания', cellFilter: "date:'dd.MM.yyyy'" },
{ field: "task_status", displayName: 'Статус', cellTemplate: "<div class='ui-grid-cell-contents status-{{ COL_FIELD }}'>{{['В процессе выполнения', 'Выполнено', 'Невыполнимо'][COL_FIELD]}}</div>"}
]
}
.factory 'Task', ($resource) ->
$resource('/api/it_works/:id.json')
When in looks like that (it have 10 columns), it looks fine.
But if I add one more column (or double any existing):
{ field: "performer", displayName: 'Исполнитель' },
It becomes look like that:
So, it renders only 4 columns. But why? How to fix it?
i have come with this issue and have solved it.
First, you should add ui-grid-auto-resize to your html:
<div ui-grid="gridOptions" ui-grid-pagination ui-grid-resize-columns ui-grid-auto-resize
ui-grid-selection class="grid"></div>
Then, you should add ui.grid.autoResize to your js:
angular.module('it.works', ['ngResource','ngAnimate', 'ngSanitize', 'ui.grid', 'ui.grid.pagination','ui.grid.autoResize','ui.grid.selection', 'ui.grid.resizeColumns'])
.controller 'ItWorksCtrl', ($scope, Task) ->
$scope.worksTable = {
data: Task.query(),
columnDefs: [
{ field: "created_at", cellFilter: "date:'dd.MM.yyyy'", displayName: 'Дата создания' },
{ field: "task", cellFilter: "limitTo:300", displayName: 'Описание задачи' },
{ field: "performer", displayName: 'Исполнитель' },
{ field: "task_type", displayName: 'Срочность' },
{ field: "is_orgtechnik_task", displayName: 'Оргтехника', cellTemplate: "<div class='ui-grid-cell-contents'><i class='fa {{ COL_FIELD == true && \"fa-check\" }}'></i></div>" },
{ field: "department", displayName: 'Подразделение' },
{ field: "customer", displayName: 'Заказчик' },
{ field: "customer_telephone", displayName: 'Телефон заказчика' },
{ field: "end_date", displayName: 'Дата окончания', cellFilter: "date:'dd.MM.yyyy'" },
{ field: "task_status", displayName: 'Статус', cellTemplate: "<div class='ui-grid-cell-contents status-{{ COL_FIELD }}'>{{['В процессе выполнения', 'Выполнено', 'Невыполнимо'][COL_FIELD]}}</div>"}
]
}
.factory 'Task', ($resource) ->
$resource('/api/it_works/:id.json')