populate Dropdownlist in ui grid dynamically - angularjs

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.

Related

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

How to get selected rows id in ng-grid(AngularJS)

I wish deleted selected rows.so i want to get selected ids
$scope.gridOptions = {
data: 'myData',
enablePaging: true,
showSelectionCheckbox :true,
resizable :true,
showFooter: true,
multiSelect: true,
selectedItems:$scope.mySelections,
totalServerItems:'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions,
afterSelectionChange: function () {
$scope.selectedIDs = [];
angular.forEach($scope.mySelections, function ( item ) {
$scope.selectedIDs.push(item.ID);
});
},
columnDefs: [
{ field: 'iSchl_Id', displayName: 'ID' },
{ field: 'vSchl_Name', displayName: 'School Name' },
{ field: 'vCity', displayName: 'City' },
{ field: 'vState', displayName: 'State' },
{ field: 'vCountry', displayName: 'Country' },
{ field: 'vEmail', displayName: 'Email' },
{ field: 'iStatus', displayName: 'Status' },
{ field: '', cellTemplate: '<button ng-click="edit(row.entity)" title="Edit" class="icon-edit edt-btn"></button><button ng-click="delete(row.entity)" title="Delete" class="icon-trash dlt-btn"></button>',displayName: 'Action'}
],
};
I have used dynamic data in grid.I have tried How to get the cell value from ng-grid Example but i not getting selectedIDs.I getting error: item are not defined
Deleteall function :
$scope.deleteall = function() {
var verify=confirm('Are you sure to want this delete all selected record?');
if(verify==true)
{
//Please give me logic of selected ids
}
};

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.

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

how to use ng-grid to update cells with $http?

I am new to angular and am trying to make a CRUD app with the ng-grid plugin. I found an example from the web that gets me the info I need, but not a good explanation on how to update the info using a REST route. Here is the code:
var cellEditableTemplate = "";
// Configure ng-grid
$scope.gridOptions = {
data: 'myData',
enableCellEdit: true,
multiSelect: false,
columnDefs: [
{ field: 'Id', displayName: 'Id' },
{ field: 'Name', displayName: 'Name', enableCellEdit: true, editableCellTemplate: cellEditableTemplate },
{ field: 'Description', displayName: 'Description', enableCellEdit: true, editableCellTemplate: cellEditableTemplate }
]
};
// Update Entity on the server side
$scope.updateEntity = function (column, row) {
console.log(row.entity);
console.log(column.field);
// code for saving data to the server...
// row.entity.$update() ... <- the simple case
}
How do I use the following from the example to update my model?
row.entity.$update()
Inject $http into your controller.
Then in your $scope.updateEntity:
$scope.updateEntity = function() {
$http.get('getDataFromServerUrl').success(function(data) {
//update data
$scope.gridOptions.data = data;
}).error(function(err) {
console.log('Error getting data', err);
});
}
and then your data will be updated, as $http activate the $digest cycle.

Resources