Ag-grid cell rendering to check for conditions - angularjs

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.

Related

Save the state of ag-grid in angularjs

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);
});
}

populate Dropdownlist in ui grid dynamically

i have spent lots of hours finding a solution but no success every time i am finding a solution it ends up with static data not from any web API or database. i want dynamic data to be populated in drop down list in UI grid. i have read in one blog in which guy was saying for dynamic data we have to use editDropdownRowEntityOptionsArrayPath but i did not find any useful solution. any one can provide any useful information than i will be vary thankful. thanks in advance. this is what i have done.
$scope.listOptions = []; $scope.ddlist = [];
$http.get('http://localhost:26413/api/MenuVDN/GetVDNList')
.then(function (data) {
$scope.listOptions = data;
$scope.ddlist = $scope.listOptions.data.Table;
console.log($scope.ddlist);
})
$scope.gridOptions = {
enableColumnResizing: true,
enableSorting: true,
enableCellSelection: true,
canSelectRows: true,
// enableCellEdit: true,
columnDefs: [
{ field: 'NameEn', displayName: ' Menu Name', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'asc' }, width: '25%' },
{ field: 'id', displayName: 'ID' },
{ field: 'language', displayName: 'VDN Language', grouping: { groupPriority: 1 }, sort: { priority: 1, direction: 'asc' } },
{ field: 'vdnname', displayName: 'VDN Name' },
{
field: 'vdnnum', displayName: 'VDN Number',
editableCellTemplate: 'ui-grid/dropdownEditor',
// editDropdownIdLabel: 'id',
editDropdownValueLabel: 'value',
// enableFocusedCellEdit: true,
enableCellEditOnFocus :true,
enableCellEdit: true,
editType: 'dropdown',
editDropdownRowEntityOptionsArrayPath : $scope.ddlist
// , cellEditableCondition: function( $scope ) { return true; }
}
]
};
plus i am getting response from webapi in json format like this.
{"Table":[{"id":2,"value":"AR-BOOKING-NEW (7101)"},
{"id":3,"value":"EN-BOOKIN-NEW (7102)"},
{"id":4,"value":"AR-BOOKING-CANCEL (7103)"},
{"id":5,"value":"EN-BOOKING-CANCEL (7104)"},
{"id":6,"value":"AR-BOOKING-MODIFY (7105)"}]}
$scope.columns = completedFiles.columns;
$scope.rows = completedFiles.rows;
//prepare custom column for ui-grid
var customColumns = [];
angular.forEach($scope.columns, function(column) {
customColumns.push({
field : column.fieldName,
displayName : column.displayName,
editable : column.editable,
dataType : column.dataType,
});
}
});
angular.forEach(customColumns, function(customColumn) {
customColumn['width'] = 200;
if (customColumn.dataType === 'dropDown') {
customColumn['cellTemplate'] = "<div class='ui-grid-cell-contents' id='col-description'><select class="form-control" data-ng-options="item in grid.appScope.arrayName track by item" ><option value="" selected hidden />/></select></div>";
customColumn['width'] = 180;
}
});
You can create custom template like above and after that just assign in $scope.gridOptions customColumns to columnDefs rather then defining the column definition there.

cellEditableCondition based on rowindex in ui-grid

I want to enable cell edit based on row index
columnDefs: [
{
field: "Name",
name: "Name",
enableCellEdit: true,
cellEditableCondition: 'row.rowIndex == 2',
cellTemplate: '<div class="ui-grid-cell-contents">{{}}</div>'
}
but above code is not working. If i pass true in cellEditableCondition it works fine. I think row.rowIndex is not giving index. I was able to get row index in cell template as below,
but if i write same code in cellEditableCondition it wont work.
field: "Name",
name: "Name",
enableCellEdit: true,
cellEditableCondition: 'grid.renderContainers.body.visibleRowCache.indexOf(row) == 2', // not working
cellTemplate: '<div class="ui-grid-cell-contents">{{grid.renderContainers.body.visibleRowCache.indexOf(row)}}</div>' //working
Please help me to get rowindex in cellEditableCondition
You should pass a function like this -
cellEditableCondition:
function($scope) {
return $scope.grid.renderContainers.body.visibleRowCache.indexOf($scope.row) == 2;
}

Angular UI Grid how to show multiple fields for the single column

I'm using Angular Ui Grid.How can I show multiple fields for the single column ? Thanks.
I need to show both streetNumber and StreetName on the same column.How can I do that ?
vm.propertyListGridOptions = {
appScopeProvider: vm,
flatEntityAccess: false,
fastWatch: true,
showHeader: false,
columnDefs: [
{
name: app.localize('IplNumber'),
field: 'id',
width: 100,
},
{
name: app.localize('BrAddress'),
field: 'address.streetNumber',
width: 140,
}
],
data: []
};
You can use custom template like this
$scope.gridOptions['columnDefs'] = [
{field: 'name', displayName: 'Name'},
{field: 'options',displayName: 'Options', cellTemplate: '<span>{{row.entity.streetNumber}} {{row.entity.StreetName}}</span>'}
];
You can also refer this page for documentation for custom templates http://ui-grid.info/docs/#/tutorial/317_custom_templates

Ng Grid column totals. Have I done correctly?

I have a ng-grid built with following JSON
[{"TankName":"Tnk1","UseFuel":"100","UnusedFuel":"200"},
{"TankName":"Tnk2","UseFuel":"150","UnusedFuel":"600"},
{"TankName":"TOTAL","UseFuel":"0","UnusedFuel":"0"}]
I have configured a NG-GRID to dispay. Grid will display as below
below is the Grid-otions
columnDefs: [
{ field: 'TankName', displayName: 'Fuel Tank', enableCellEdit: false,},
{ field: 'UseFuel', displayName: 'Use Fuel', editableCellTemplate: '<input ng-input="COL_FIELD" ng-model="COL_FIELD"/>' },
{ field: 'UnusedFuel', displayName: 'Unused Fuel', editableCellTemplate: '<input ng-input="COL_FIELD" ng-model="COL_FIELD"/>' }
]
I want to put the column totals (Bottom Row) when user edit something on the gird. I have to show them in "TOTAL" row. I cannot use FooterTemplate since its not suiting my need
Below is my code in controller
$scope.$on('ngGridEventEndCellEdit', function (data) {
var totalRow;
angular.forEach(a.gridOptions_all.ngGrid.data, function (row) {
if (row.TankName.toString().toUpperCase() != 'TOTAL') {
totalUseFuel += Number(row.UseFuel);
totalUnUseFuel += Number(row.UnusedFuel);
}
else {totalRow = row;}
});
totalRow.UseFuel= totalUseFuel ;
totalRow.UnusedFuel= totalUnUseFuel ;
});
here a plunker. Could some say whether is there a better option
Regarding the picture you placed in the question I would solve it like this:
columnDefs: [{
field: 'TankName',
displayName: 'Tank',
enableCellEdit: false,
cellEditableCondition: 'newFunc(row);'
}, {
field: 'UseFuel',
displayName: 'Ballast Fuel',
editableCellTemplate: '<input ng-input="COL_FIELD" ng-model="COL_FIELD"/>'
}, {
field: 'UnusedFuel',
displayName: 'Trapped Fuel',
cellEditableCondition: 'row.rowIndex != 2',
editableCellTemplate: '<input ng-input="COL_FIELD" ng-model="COL_FIELD"/>'
}, {
displayName: 'Total',
cellTemplate: '<div>{{getTotal(row.entity.UseFuel,row.entity.UnusedFuel)}}<div>'
}
]
};
$scope.getTotal = function(uf, uuf) {
return Number(uf) + Number(uuf);
}
Note the cellTemplate and the getTotal function.
Look at this Plunker to see this updating while you type.

Resources