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,
}
Related
I am trying to sum two columns in a function then display their result in the ui grid. any ideas about how to do this, then save the ui grid content in the database?
see the picture
so in my case : a and b are binded from the database, while I want angularjs to calculate their sum and add it in the column "Quantite reelle".
this is my grid code $scope.gridOptions = {
showGridFooter: true,
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
gridApi.core.on.renderingComplete($scope, function () {
$timeout(function () {
var gridBodyElem = document.getElementById(gridApi.grid.id + '-grid-container');
gridApi.grid.element.on('mouseup', handleGridClick);
});
});
}
};
$scope.gridOptions.columnDefs = [
{ name: 'Num', enableHiding: false, enableColumnMenu: false, enableCellEdit: false, width: '5%' },
{ name: 'CodeArticle', enableHiding: false, enableColumnMenu: false, displayName: 'Code Article ', width: '10%' },
{ name: 'Ref', enableHiding: false, enableColumnMenu: false, displayName: 'Référence ', width: '10%' },
{ name: 'Designation', enableHiding: false, enableColumnMenu: false, displayName: 'Désignation ', width: '30%' },
{ name: 'Stock', enableHiding: false, enableColumnMenu: false, displayName: "Qté théorique (a)", width: '13%' },
{ name: "ajust", enableHiding: false, enableColumnMenu: false, displayName: "Ajustement (b)", width: '12%' },
{ name: "sum", enableHiding: false, enableColumnMenu: false, displayName: "Quantité Réelle(a+b)", width: '14%' },
{ name: "motif", enableHiding: false, enableColumnMenu: false, displayName: "Motif", width: '20%' }
];
`
thank you guys.
You need to set column field property to expression.
$scope.gridOptions.columnDefs = [
{ name: "sum", enableHiding: false, enableColumnMenu: false, field:'CalculateSum(a,b)', displayName: "Quantité Réelle(a+b)", width: '14%' }
];
Here a & b are respective column names.
You can try this:
$scope.gridApi.grid.columns[column a].getAggregationValue() +
$scope.gridApi.grid.columns[column b].getAggregationValue()
$scope.gridOptions.columnDefs = [
{ name: 'Num', enableHiding: false, enableColumnMenu: false, enableCellEdit: false, width: '5%' },
{ name: 'CodeArticle', enableHiding: false,field:'CodeArticle', enableColumnMenu: false, displayName: 'Code Article ', width: '10%' },
{ name: 'Ref', enableHiding: false,enableColumnMenu: false, displayName: 'Référence ', width: '10%' },
{ name: 'Designation', enableHiding: false, enableColumnMenu: false, displayName: 'Désignation ', width: '30%' },
{ name: 'Stock', enableHiding: false,field:'Stock', enableColumnMenu: false, displayName: "Qté théorique (a)", width: '13%' },
{ name: "ajust", enableHiding: false, field: 'ajust', enableColumnMenu: false, displayName: "Ajustement (b)", width: '12%' },
{ name: "sum", enableHiding: false, enableColumnMenu: false, field: 'CalculateSum(ajust,Stock)', displayName: "Quantité Réelle(a+b)", width: '14%' },
{ name: "motif", enableHiding: false, enableColumnMenu: false, displayName: "Motif", width: '20%' }
];
$scope.CalculateSum = function (ajust, Stock) {
return ajust + Stock;
};
Following Tutorial: 323 More Binding examples I created a Plunker, using a filter calculateSum to calculate the sum of both fields.
angular.module('app', ['ngAnimate', 'ngTouch', 'ui.grid'])
.controller('MainCtrl', MainCtrl)
.filter('calculateSum', function () {
return function (input, a, b) {
return input[a]+input[b];
};
});;
MainCtrl.$inject = ['$http', 'uiGridConstants'];
function MainCtrl($http, uiGridConstants) {
var vm = this;
vm.gridOptions = {
enableFiltering: true,
onRegisterApi: function(gridApi){
vm.gridApi = gridApi;
},
columnDefs: [
{ field: 'name'},
{ field: 'num1'},
{ field: 'num2'},
{ name: 'sum', field: uiGridConstants.ENTITY_BINDING, cellFilter: 'calculateSum:"num1":"num2"' }
]
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.then(function(response) {
response.data.forEach(function(row){
row.num1 = row.age;
row.num2 = row.age*2;
});
vm.gridOptions.data = response.data;
});
}
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);
});
}
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 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')
I have a angular directive which returns the kendo grid data source values (which is gridDataDisplayed). With the same data source, i have to bind it to a nested grid in detailInit.
scope.gridsource = new kendo.data.DataSource({
pageSize: options.pSize,
transport: {
read: function (options) {
scope.getDataMethod({ pageDetails: options }).then(function (gridDataDisplayed) {
options.success(gridDataDisplayed);
}, function (error) {
//error
});
}
},
detailInit: detailInitMethod
});
In the detailInitMethod i have the use the same data returned from service call and display only few columns from "gridDataDisplayed". How can i bind this to nested grid?
In my directive the template code is:
template: '<div><kendo-grid k-options="gridOptions" k-data-source="gridDataSource"></kendo-grid></div>',
Thanks in advance.
You can use the detail-template directive. Here is how:
<div ng-controller="MyCtrl">
<kendo-grid options="mainGridOptions" k-data-source="gridDataSource">
<div k-detail-template>
<div kendo-grid k-options="detailGridOptions"></div>
</div>
</kendo-grid>
</div>
<script>
angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", function($scope){
$scope.gridDataSource = {
type: "odata",
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
},
pageSize: 5,
serverPaging: true,
serverSorting: true
};
$scope.mainGridOptions = {
sortable: true,
pageable: true,
dataBound: function() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [{
field: "FirstName",
title: "First Name",
width: "120px"
},{
field: "LastName",
title: "Last Name",
width: "120px"
}]
};
$scope.detailGridOptions = {
scrollable: false,
sortable: true,
dataSource: $scope.gridDataSource,
pageable: true,
columns: [
{ field: "City", title:"City", width: "56px" },
{ field: "Address", title:"Address", width: "110px" }
]
};
});
</script>
And a live demo: http://dojo.telerik.com/#korchev/UFIqa