using expandable Angular js ui grid - angularjs

I am using Expandable UI Grid.
My data is shown in grid which is expanded on click and grid is refreshed every 5 secs.
If I expand a row then it is collapsed every 5 seconds as the grid refreshes.
How can I maintain the row expansion when the grid refreshes?
Code
$scope.fillProductList = function () {
$http({
method: 'GET',
url: getJobs,
data: {}
}).success(function (result) {
$scope.showSubListGrid = false;
$scope.myData = '';
var gridDataWithDownload = result;
//grid data
$scope.myData = gridDataWithDownload;
$scope.gridOptionsCategory.data = gridDataWithDownload;
// $scope.refresh = false;
timer = $timeout(function () {
$scope.fillProductList();
}, timeOutStamp);
}).error(function (result) {
timer = $timeout(function () {
$scope.fillProductList();
}, timeOutStamp);
});
};
$scope.gridOptionsCategory = {
useExternalPagination: true,
expandableRowHeight: 300,
enableSorting: true,
data: $scope.myData,
enableColumnResizing: true,
enableGridMenu: false,
expandableRowTemplate: 'griddata.html',
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
// gridApi.expandable.toggleRowExpansion($scope.gridApi.grid.row[0].entity);
gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
$scope.gridApi.grid.modifyRows($scope.gridOptionsCategory.data);
$scope.gridApi.selection.selectRow($scope.gridOptionsCategory
.data[0]);
//$scope.gridOptionsCategory.expandableRowHeight = 500;
//$timeout.cancel(timer);
if (row.isExpanded) {
row.entity.components = JSON.parse(row.entity.components)
this.scope.gridOptionsCategory.expandableRowScope = row.entity;
// $scope.GridOptions.expandableRowScope = row.entity.components;
}
if (!row.isExpanded) {
timer = $timeout(function () {
$scope.fillProductList();
}, timeOutStamp);
}
});
},
enableHorizontalScrollbar: 0,
//enableVerticalScrollbar:0,
//useExternalSorting: true,
columnDefs: [{
field: 'filtertoggle',
displayName: '',
visible: true,
headerCellTemplate: '' +
'<button id=\'toggleFiltering\' style= "padding:3px 7px;" ng-click="grid.appScope.toggleFiltering()" class="btn btn-warning glyphicon glyphicon-filter">' +
'</button>'
},
{
name: 'Job Name',
field: 'name',
width: '20%',
enableCellEdit: false,
enableHiding: true,
enableGrouping: false,
// enableFiltering: true,
filter: {
term: $scope.filterOptions.filterText
}
},
{
name: 'Profile',
field: 'profile',
width: '15%',
enableCellEdit: false,
enableHiding: true,
enableGrouping: false
}, {
name: 'Progress',
field: 'progress',
enableSorting: true,
width: '18%',
enableCellEdit: false,
enableHiding: true,
enableGrouping: false,
// enableFiltering: true,
cellTemplate: statusTemplate
}
]
};

gridApi.core.on.rowsRendered(scope,() => {
if (!gridApi.grid.expandable.expandedAll && !initialized)
{ gridApi.expandable.expandAllRows();
initialized = true;
}
});
Can you check with these code. You might get some idea.

Related

how to pass the selected row item in angular ui-grid to fetch data for another ui-grid

I have 2 ui-grids displaying data using 2 different controllers, each controller calling a different service. (service uses ngresource and not http.)
My need is : when one row is selected in 1st grid(vendors), the 2nd grid(contracts) should get data only where the value matches the id that was fetched in the first grid.
So basically when the 1st grid vendors $scope.gridApi.selection.on.rowSelectionChanged event is triggered the contracts.query should get triggered with the VEID value of the row selected.
I am new to angular, so not able to figure out exactly where to pass the values and where to add in function to achieve this. I saw the article on $emit and $on, but not clear on it. Also my service uses $ngresource and QUERY method , while most examples are using $http or POST method. Please help!
//app.js
(function () {
'use strict';
angular.module('VendorApp', ['ui.grid', 'ui.grid.pagination', 'ui.grid.selection','ang_venservice','ang_contservice','ui.grid.pinning']);
})();
//vendor controller
(function () {
'use strict';
angular
.module('VendorApp')
.controller('ang_vencontroller', ang_vencontroller);
ang_vencontroller.$inject = ['$scope', 'vendors','contracts','$timeout', 'uiGridConstants'];
function ang_vencontroller($scope, $rootscope,vendors, $timeout, uiGridConstants)
{
$scope.vendorsvalues = vendors.query()
$scope.gridOptions = {
enableRowHeaderSelection: false,
multiSelect: false,
enableRowSelection: true,
enableSelectAll: true,
enableSorting: true,
enableFiltering: true,
enablePagination: true,
enablePaginationControls: true,
paginationCurrentPage: 1,
paginationPageSize: 100,
maxVisibleColumnCount: 200,
columnDefs: [
{ name: 'VENDORID', field: 'MVE_VEID' },
{ name: 'NAME', field: 'VE_NAME' },
{ name: 'ADDR1', field: 'VE_ADDR1' }
],
data: $scope.vendorsvalues
};
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
$timeout(function () {
$scope.gridApi.selection.on.rowSelectionChanged($scope, function (row) {
$scope.value = row.entity.MVE_VEID;
$scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows();
//$scope.contractvalues =function(){$rootScope.$emit( contracts.query({ id: $scope.value }))};
});
//contract controller
(function () {
'use strict';
angular
.module('VendorApp')
.controller('ang_contcontroller', ang_contcontroller);
ang_contcontroller.$inject = ['$scope', 'contracts'];
function ang_contcontroller($scope, $rootscope,contracts) {
$scope.contractvalues = contracts.query({ id: $scope.value });
$scope.gridoptions2 = {
enableRowHeaderSelection: false,
multiSelect: false,
enableRowSelection: true,
enableSelectAll: true,
enableSorting: true,
enableFiltering: true,
enablePagination: true,
enablePaginationControls: true,
paginationCurrentPage: 1,
paginationPageSize: 100,
maxVisibleColumnCount: 200,
columnDefs: [
{ name: 'CONTRACTID', field: 'MCO_COID' },
{ name: 'NAME', field: 'CO_DESC' },
{ name: 'VENDORID', field: 'MCO_VEID' }
],
data: $scope.contractvalues
};
}
})();
//contract service
(function () {
'use strict';
var ang_contservice = angular.module('ang_contservice', ['ngResource']);
ang_contservice.factory('contracts', ['$resource', function ($resource)
{
return $resource('/api/ContractsAPI/:id', { id: 0 }, { query: { method: 'GET', params: {}, isArray: true } });
}])
})();
<body ng-cloak>
<h4>VENDORS</h4>
<div ng-controller="ang_vencontroller" >
<div id="grid1" ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid"></div>
<strong>SelectedRowCount:</strong> <span ng-bind="mySelectedRows.length"></span>
<br />
<strong>SelectedVendor:</strong> <span ng-bind="value"></span>
</div>
<br>
<br>
<h4>CONTRACTS</h4>
<div ng-controller="ang_contcontroller">
<div id="grid2" ui-grid="gridoptions2" ui-grid-pagination ui-grid-selection class="grid"></div>
</div>
</body>
</html>
I got this working.
I had to have both the grids in the same controller and that fixed the issue.
This is because the $scope.GridApi is not available between controllers.
U may be able to achieve grids to interact in different controllers using Controller AS , but for now, this serves my purpose.
Below is the working controller code:
(function () {
'use strict';
angular
.module('VendorApp')
.controller('ang_vencontroller', ang_vencontroller);
ang_vencontroller.$inject = ['$scope','$rootScope', 'vendors','contracts','$timeout', 'uiGridConstants'];
function ang_vencontroller($scope, $rootScope, vendors, contracts, $timeout, uiGridConstants) {
$scope.value = 0;
$scope.vendorsvalues = vendors.query();
$scope.gridOptions = {
enableRowHeaderSelection: false,
multiSelect: false,
enableRowSelection: true,
enableSelectAll: true,
enableSorting: true,
enableFiltering: true,
enablePagination: true,
enablePaginationControls: true,
paginationCurrentPage: 1,
paginationPageSize: 100,
maxVisibleColumnCount: 200,
columnDefs: [
{ name: 'VENDORID', field: 'MVE_VEID' },
{ name: 'NAME', field: 'VE_NAME' },
{ name: 'ADDR1', field: 'VE_ADDR1' }
],
data: $scope.vendorsvalues
};
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
console.info("grid api 1 registered", $scope.gridApi);
$timeout(function () {
$scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
$scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows();
$scope.value = $scope.mySelectedRows[0].MVE_VEID;
$scope.gridApi.selection.on.rowSelectionChanged($scope, function (row) {
$scope.value = row.entity.MVE_VEID;
$scope.contractvalues = contracts.query({ id: $scope.value });
console.log("scope.contractvalues:", $scope.contractvalues);
$scope.gridoptions2.data = $scope.contractvalues;
$scope.gridApi2.core.notifyDataChange(uiGridConstants.dataChange.ALL);
});
});
};
$scope.contractvalues = contracts.query({ id: $scope.value });
$scope.gridoptions2 = {
enableRowHeaderSelection: false,
multiSelect: false,
enableRowSelection: true,
enableSelectAll: true,
enableSorting: true,
enableFiltering: true,
enablePagination: true,
enablePaginationControls: true,
paginationCurrentPage: 1,
paginationPageSize: 100,
maxVisibleColumnCount: 200,
columnDefs: [
{ name: 'CONTRACTID', field: 'MCO_COID' },
{ name: 'NAME', field: 'CO_DESC' },
{ name: 'VENDORID', field: 'MCO_VEID' }
],
data: $scope.contractvalues,
onRegisterApi: function (gridApi) {
$scope.gridApi2 = gridApi;
}
};
$scope.gridoptions2.onRegisterApi = function (gridApi) {
$scope.gridApi2 = gridApi;
console.info("***grid api 2 registered***", $scope.gridApi2);
};
}
})();

newRawData.forEach is not a function in ui-grid

I search for this error but not able to fix it.Am new to angular.Dont know exactly whats going wrong.
Html:
<div class="row gridContainer" ng-controller="tripsGridController">
<div ui-i18n="{{::selectedLanguageName}}">
<div ui-grid="gridOptionsTrips" ui-grid-selection ui-grid-resize-columns ui-grid-move-columns ></div>
</div>
</div>
Angular code:
$scope.gridOptionsTrips = {};
$scope.gridDataSourceTrips = [];
var ROW_HEIGHT = 30;
// to show data on Grid
$scope.gridOptionsTrips = {
enableRowSelection: true,
enableRowHeaderSelection: true,
enableSorting: true,
multiSelect: false,
rowHeight: ROW_HEIGHT,
virtualizationThreshold: 10,
fastWatch: false,
enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
data: 'gridDataSourceTrips',
appScopeProvider: $scope,
showColumnMenu: true,
enableSelectAll: false,
noUnselect: true,
enableCellSelection: true,
rowTemplate: '<div ng-click=\"grid.appScope.onTripsGridRowClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" class=\"ui-grid-cell\" ng-class=\"{ \'ui-grid-row-header-cell\': col.isRowHeader }\" ui-grid-cell></div>'
};
$scope.onTripsGridRowClick = function (row) {
$scope.gridApi.selection.selectRow(row.entity);
};
$scope.gridColDefsTrips = function () {
var idTemplate = '<div></div>';
var sTemplate = '<div></div>';
var speedTemplate = '<div></div>';
var directionTemplate = '<div></div>';
var timeTemplate = '<div></div>';
var kmCounterTemplate = '<div></div>';
var driverNameTemplate = '<div></div>';
return [
{ name: "CARDRIVER", displayName: "CARDRIVER", field: 'UserId', cellTemplate: idTemplate, enableColumnMenu: false, headerCellFilter: 'translate', width: 150, showInColumnFilter: true },
{ name: 'STARTEND', displayName: 'STARTEND', field: 'Departure.DateTime', cellTemplate: idTemplate, width: 70, enableColumnMenu: false, headerCellFilter: 'translate', showInColumnFilter: true },
{ name: 'STARTEND', displayName: 'STARTEND', field: 'Destination.DateTime',cellTemplate: idTemplate, enableColumnMenu: false, headerCellFilter: 'translate', width: 80, showInColumnFilter: true },
{ name: 'TRIPLENGTH', displayName: 'TRIPLENGTH', field: 'Distance', cellTemplate: idTemplate, enableColumnMenu: false, headerCellFilter: 'translate', width: 150, showInColumnFilter: true }
];
};
$scope.gridDataSourceTrips = tripsDetailsService.GetAllTripsByWeek('2014-01-10', '2014-01-14', 1, 20);
$scope.gridOptionsTrips.columnDefs = $scope.gridColDefsTrips();

Updating cell data in ui-grid without page refresh

I have a table that I made using ui-grid. The table displays information about a list of news stories. In the final column, I am giving the user the ability to edit, delete, and/or make a news story.
Everything seems to be working fine with that - I am able to have a modal pop up, and after entering in the required information, I can see my data change on the server. If I refresh the page, I can also see my data change on the table. However, I would like the cell data to change without page refresh. It doesn't seem to be binding to my news data.
Here is the ui-grid:
$scope.news = getAdminNews.results;
/**
* ui-grid implementation
*/
$scope.gridOptions = {
data: 'news',
enableColumnResizing: true,
enableFiltering: true,
enableGridMenu: false,
enableColumnMenus: false,
paginationPageSizes: [25,50,75],
paginationPageSize: 25,
rowHeight: 75
};
$scope.gridOptions.columnDefs = [{
displayName: 'Title',
field: 'title.rendered',
filterCellFiltered: true,
sortCellFiltered: true,
width: '20%'
}, {
displayName: 'Body',
field: 'body',
width: '20%'
}, {
displayName: 'Created',
field: 'created',
type: 'date',
cellFilter: 'date:"yyyy-MM-dd"',
filterCellFiltered: true,
sortCellFiltered: true,
width: '20%',
sort: {
priority: 0
}
},
{
displayName: 'Actions',
displayName: 'Actions',
width: '20%',
enableSorting: false,
enableFiltering: false,
field: 'actions',
cellTemplate: 'table-cell-actions'
}
];
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridApi = gridApi;
};
And one part of my controller which is working successfully:
$scope.newPost = function() {
ngDialog.openConfirm({
template: 'modalPostNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
var newPost = {
"id": 0,
"title": $scope.newPostForm.title
}
AdminNews.save(newPost);
toaster.pop('success', 'Updated', 'News item updated successfully.');
});
}
I needed to update my $scope.news data that ui-grid was populating the table with. Here is what my controller looks like now:
$scope.newPost = function() {
ngDialog.openConfirm({
template: 'modalPostNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
var newPost = {
"id": 0,
"title": $scope.newPostForm.title
}
AdminNews.save(newPost).$promise.then(function(response) {
var myObj = {
"id": response.data.id,
"title": {
"rendered": response.data.title
}
}
$scope.news.push(myObj);
});
toaster.pop('success', 'Updated', 'News item updated successfully.');
});
}

ng-grid paging: total items and page count is wrong

I have followed several threads in here related to the issue but couldn't find the issue with my code. I have a paged ng-grid, but the total item count (bottom left corner) and the total page count x/n is wrong. When I should have 14 as total items and 3 as total pages for a page size of 5, I see the total count as 5 and the total pages as 1. However, I can navigate to the other pages with the arrow icon.
Here is my code:
vm.gridOptions = {
data: "vm.pagedDataList",
rowHeight: 35,
enableCellSelection: false,
enableRowSelection: true,
multiSelect: false,
columnDefs: [
{ field: 'locationId', displayName: localize.getLocalizedString('_LocationCode_'), visible: false},
{ field: 'locationCode', displayName: localize.getLocalizedString('_LocationCode_'), width: '10%', cellTemplate: tooltipTemplateUrl },
{ field: 'locationTypeName', displayName: localize.getLocalizedString('_Locationtype_'), width: '15%', cellTemplate: tooltipTemplateUrl },
{ field: 'locationName', displayName: localize.getLocalizedString('_LocationName_'), width: '15%', cellTemplate: tooltipTemplateUrl },
{ field: 'locationDisplayName', displayName: localize.getLocalizedString('_LocationDisplayName_'), width: '15%', cellTemplate: tooltipTemplateUrl }
],
enablePaging: true,
showFooter: true,
pagingOptions: { pageSizes: [5,10], pageSize: 5, currentPage: 1 },
totalServerItems: 'vm.locationList.length'
};
$scope.$watch('vm.gridOptions.pagingOptions', function (newVal, oldVal) {
//if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
vm.getPagedDataAsync(vm.gridOptions.pagingOptions.pageSize, vm.gridOptions.pagingOptions.currentPage, null);
//}
}, true);
vm.setPagingData = function (data, page, pageSize) {
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
vm.pagedDataList = pagedData;
vm.gridOptions.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
vm.getPagedDataAsync = function (pageSize, page) {
vm.setPagingData(vm.locationList, page, pageSize);
};
Then I call this in the init() method, after the data is loaded;
vm.getPagedDataAsync(vm.gridOptions.pagingOptions.pageSize, vm.gridOptions.pagingOptions.currentPage);
change line
totalServerItems: 'vm.locationList.length'
to
totalServerItems: 'totalServerItems',
and
vm.gridOptions.totalServerItems = data.length;
to
$scope.totalServerItems = data.length;

Populate ng-grid by another grid selection

I am trying to populate a ng-grid based on the JSON array returned from a selection of a first ng-grid. As of right now I can get the JSON array displayed onto the screen but I cannot navigate deeper into the JSON array or get anything to display in the second grid. I have the controller code attached and the plnkr can be found at http://plnkr.co/edit/nULoI4?p=info.
'use strict';
function ArticleDataCtrl($rootScope, $scope, articleDataService) {
articleDataService
.getArticles()
.then(
function(articles) {
$rootScope.articles = articles;
$scope.articleGridItems = articles.data.specialMerchandise.specialMerItem;
});
$scope.articleGrid = {
data: 'articleGridItems',
showGroupPanel: false,
multiSelect: true,
checkboxHeaderTemplate: '<input class="ngSelectionHeader" type="checkbox" ng-click="getDeliveryLocations()" ng-model="allSelected" ng-change="toggleSelectAll(allSelected)"/>',
showSelectionCheckbox: true,
selectWithCheckboxOnly: true,
enableColumnResize: true,
selectedItems: [],
columnDefs: [{
field: 'soMerArticleNbr',
displayName: 'Article'
}, {
field: 'soMerOrdQty',
displayName: 'Qty'
}, {
field: 'soArtDeliveryCode',
displayName: 'Delivery Code'
}, {
field: 'dsgnSysRecDesc',
displayName: 'Description'
}]
};
//This is not being called on header template click
$scope.getDeliveryLocations = function() {
$scope.deliveryLocationData = $scope.commonDeliveryLocations;
};
$scope.selections = $scope.articleGrid.selectedItems;
var jsonObject = JSON.stringify($scope.selections);
//Thought a json problem occured here...was wrong
$scope.test = jsonObject.deliveryLocations;
$scope.deliveryGrid = {
data: 'selections',
showGroupPanel: false,
multiSelect: false,
columnDefs: [{
displayName: 'Delivery Methods'
}]
};
}
myApp.controller('ArticleDataCtrl', ['$rootScope', '$scope',
'articleDataService', ArticleDataCtrl
]);
So instead of trying to use angular's built in checkboxes I used my own with a custom method on ng-click. Here is the code and the plunker demonstrating the functionality is http://plnkr.co/edit/nULoI4?p=info.
'use strict';
function ArticleDataCtrl($rootScope, $scope, articleDataService) {
articleDataService
.getArticles()
.then(
function(articles) {
$rootScope.articles = articles;
$scope.articleGridItems = articles.data.specialMerchandise.specialMerItem;
});
$scope.articleGrid = {
data: 'articleGridItems',
showGroupPanel: false,
multiSelect: false,
enableColumnResize: true,
selectWithCheckboxOnly: true,
columnDefs: [{
/*
headerCellTemplate: myHeaderCellTemplate,
*/
cellTemplate: '<input id="checkSlave" name="articleCheckBox" ng-checked="master" type="checkbox" ng-click="getDeliveryLocation(row.entity)" />'
}, {
field: 'soMerArticleNbr',
displayName: 'Article'
}, {
field: 'soMerOrdQty',
displayName: 'Qty'
}, {
field: 'soMerUOIDesc',
displayName: 'UOM'
}, {
field: 'soArtDeliveryCode',
displayName: 'Delivery Code'
}, {
field: 'soMerShrtMerDesc',
displayName: 'Description'
}, {
field: 'soMerDesc',
displayName: 'Vendor'
}]
};
$scope.getDeliveryLocation = function(deliveryLocation) {
$scope.deliveryLocationData = deliveryLocation.deliveryLocation;
for (var i = 0; i < $scope.deliveryLocationData.length; i++) {
var locationId = $scope.deliveryLocationData[i].dlvryLocId;
var locationDesc = $scope.deliveryLocationData[i].dlveryLocDesc;
$scope.deliveryLocationData[i].dlvryLocId = locationId + locationDesc;
}
return $scope.deliveryLocationData;
};
return $scope.deliveryLocationData;
};
$scope.deliveryGrid = {
data: 'deliveryLocationData',
showGroupPanel: false,
multiSelect: false,
columnDefs: [{
field: 'dlvryLocId',
displayName: 'Delivery Methods'
}]
};
$scope.customerGroup = {
value: 'DIY'
};
}
myApp.controller('ArticleDataCtrl', ['$rootScope', '$scope',
'articleDataService', ArticleDataCtrl
]);

Resources