ng-grid delete a row by clicking a button outside the grid - angularjs

I have an ng-grid which has the Edit and Delete buttons at the bottom of the grid. Both buttons are disabled when no rows are selected.
I want to know what the correct way to delete a row for ng-Grid, when a row is selected.
I could not find any examples from their website or their wiki

I did a quick comparison of the original and the selected... something like this:
angular.forEach($scope.gridOptions.selectedItems, function(index) {
var deleteIndex = $scope.originalResource.indexOf(index);
if (deleteIndex > -1){
$scope.originalResource.splice(deleteIndex,1);
}
});
And then to unselect the rows I did this: $scope.selections.splice(0)

use this it works for both multiple rows or single row selection
$scope.mySelections = [];
$scope.gridOptions = {
data :'data',
selectedItems : $scope.mySelections,
showSelectionCheckbox : true
}
$scope.delItem = function() {
for (var i = 0; i < $scope.mySelections.length; i++) {
var index = $scope.data.indexOf($scope.mySelections[i]);
if (index != -1) {
$scope.data.splice(index, 1);
}
}
}

Related

how to set always selected first row ui-grid

I was looking for this function thru api and tutorial but found only select the first row in the first grid init,
gridApi.selection.selectRow($scope.gridOptions.data[0]);
I was trying to use this capability inside onRegisterApi or inside filter function
$scope.filter = function() {
$scope.gridApi.grid.refresh();
$scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
}
$scope.singleFilter = function( renderableRows ){
var matcher = new RegExp($scope.filterValue);
renderableRows.forEach( function( row ) {
var match = false;
[
// 'id',
// 'study.name',
'title',
'occuredDate',
// 'eventType.name',
'description',
'createdDate' ,
// 'priority.name',
'severity.name',
'status.name',
'createdDate'
].forEach(function( field ){
if (field.indexOf('.') !== '-1' ) {
field = field.split('.');
}
if ( row.entity.hasOwnProperty(field) && row.entity[field].match(matcher) || field.length === 2 && row.entity[field[0]][field[1]].match(matcher)){
match = true;
}
});
if ( !match ){
row.visible = false;
}
});
return renderableRows;
};
but nothing helps. I need that first row always been selected even if I'm filtering data thru columns filter or with using single Filter. Is it possible in ui-grid?
my plunker
Try adding the following line to your gridApi.selection.on.rowSelectionChanged-Function:
gridApi.selection.selectRow($scope.gridOptions.data[0]);
This way row number 1 will always be selected.
A forked plunkr: plunkr
Edit:
When the first record should be always visible, add the line renderableRows[0].visible = true; to your filter function right before the return: plunkr

AngularJS dirPagination Select All Visible Rows

I'm building a CRUD data management project using Angular and the dirPagination directive and need to have a "select all" checkbox that selects all rows that are visible /without/ using jQuery.
I started with this - note - I am climbing the Angular learning curve and am aware that some/all of this may not be "the Angular way" but I also don't want to start fiddling (no pun) with the guts of dirPagination, ergo the dirPagination directive:
<tr dir-paginate-start="item in items|filter:filterFunction()|orderBy:sortPredicate:reverse| itemsPerPage: rowsPerPage">
and the individual row-checkbox
<input type="checkbox" class="rowSelector" ng-model="item.isSelected" ng-change="rowSelect($index, $event)"/> status: {{item.isSelected}}
and the related model elements:
$scope.items = [] //subsequently filled
$scope.rowsPerPage = 5;
$scope.rowSelect = function (ix, $event) {
var checked = (typeof $event == 'undefined') ? false : true;
if (!checked) { $scope.masterCheck = false; }
var rpp = $scope.rowsPerPage;
var p = $scope.__default__currentPage; //dirPagination's current page
var start = ((Math.max(0, p - 1) * rpp));
$scope.items[start + ix].isSelected = checked;
};
that works as expected. Check/uncheck a row and the {{item.isSelected}} value is updated in the model and is displayed beside the checkbox.
Then I added this /outside/ of the dirPagination repeat block:
<input type="checkbox" id="masterCheckbox" ng-model="masterCheck" ng-click="checkAll()" />
and the related function in the model:
$scope.masterCheck = false;
$scope.checkAll = function () {
var rpp = $scope.rowsPerPage;
var p = $scope.__default__currentPage; //dirPagination's current page
var start = ((Math.max(0, p - 1) * rpp));
var checked = $scope.masterCheck == true;
var rows = document.getElementsByClassName("rowSelector");
for (var ix = 0; ix < rows.length; ix++) {
rows[ix].checked = checked;
$scope.items[start + ix].isSelected = checked;
}
}
however in the checkAll() function checking/unchecking the individual rows isn't reflected in the {{item.isSelected}} display of each row.
Explicitly setting the individual item with
$scope.items[start + ix].isSelected = checked;
seems to set the 'isSelected' property of that item within the scope of the checkAll function but the row display does not change.
Clearly I have something wrong perhaps misunderstanding a Scope issue but at this point I'm stumped.
Any help greatly appreciated :-)
The light dawned, finally.
checkAll() as written tried to access each row by calculating its position using dir-paginate's __default__currentPage and Angular's row $index.
Of course that doesn't work because the items[] collection held by dir-paginate has been subjected to filtering and sorting, so while items[] do get checked (item.isSelected = true) the selected items/rows were living on non-visible pages. i.e. - we were selecting the wrong indexes.
One solution is comprised of the following -
The master checkbox
<input type="checkbox" id="masterCheckbox" ng-model="masterCheck" ng-click="checkAll()" />
The row checkbox (note function calls)
<input type="checkbox" class="rowSelector" value="{{sourceIndex('senId',item.senId)}}" ng-model="item.isSelected" ng-click="rowSelect(this)" />
the dir-paginate directive controls tag
<dir-pagination-controls on-page-change="onPageChange(newPageNumber)" max-size="15" direction-links="true" boundary-links="true" pagination-id="" template-url=""></dir-pagination-controls>
and the related $scope values and functions:
$scope.items = [];
$scope.masterCheck = false;
$scope.onPageChange = function (newPageNumber) {
//clear all selections on page change
//dir-paginate provides this hook
$scope.masterCheck = false;
for (var i in $scope.items) {
$scope.items[i].isSelected = false;
}
}
$scope.rowSelect = function (item) {
//if one is unchecked have to turn master off
if (!item.isSelected) $scope.masterCheck = false;
}
$scope.sourceIndex = function (keyName, key) {
//gets the actual items index for the row key
//see here http://stackoverflow.com/questions/21631127/find-the-array-index-of-an-object-with-a-specific-key-value-in-underscore
//for the 'getIndexBy' prototype extension
var ix = $scope.items.getIndexBy(keyName, key);
return ix;
}
$scope.checkAll = function () {
//only visible rows
var boxes = document.getElementsByClassName("rowSelector");
for (var bix in boxes) {
var ix = boxes[bix].value;
$scope.items[ix].isSelected = $scope.masterCheck;
}
}
There is probably a better way but while not highly efficient this one works well enough for common folk.
The $scope.sourceIndex() function stuffs the actual source row index into the row checkbox as its value= attribute value.
The checkAll() function then grabs all visible rows by the "rowSelector" class and then iterates through those grabbing the data index from the checkbox value and setting the appropriate item.isSelected.
The $scope.onPageChange is specified in the dir-Paginate controls directive and ensures that when the page changes, all row selections are cleared.
Happy happy.
Your variable masterCheck is being set to false in rowSelect() and subsequently in checkAll() you are setting checked to masterCheck which then is used to assign isSelected
This line is wrong:
var checked = $scope.masterCheck == true;
Because you want to flip masterCheck so it should be:
$scope.masterCheck = !$scope.masterCheck;
and then
.isSelected = $scope.masterCheck;
You weren't ever setting $scope.masterCheck to true so it was always false and since your isSelected values depended on it, they were always false. Also, this functions as a checkAll/unCheckAll to make it only check all change to the following:
$scope.masterCheck = !$scope.masterCheck;
var checked = $scope.masterCheck == true;

How to remove multiple selected rows from grid

I have grid then I can select few or all the rows and on toolbar with a "delete" button. I can delete one row, but for remove several; selected rows I don't have a method.
Can somebody help me? Thank you.
The following is for deletion of one selected row:
listeners: {
click: {
scope: this,
fn: function(sm, selection) {
var selection = this.getView().getSelectionModel().getSelection()[0];
/*if (selection.length > 1) {
store.removeAll(selection);
}*/ //This not working
else {
store.remove(selection);
}
store.sync();
}
}
}
selectionModel.getSelection() will give you array of records.
If you are able to get all the selected rows you can access each row in a loop and also you can leave some of the selected rows.
onDeleteClick : function() {
var studentGrid = this.getStudentGrid();
var studentStore = studentGrid.getStore();
var selectedRows = studentGrid.getSelectionModel().getSelection();
if (selectedRows.length) {
studentStore.remove(selectedRows);
} else {
Ext.Msg.alert('Status', 'Please select at least one record to delete!');
}
}

ng-grid - Keep overall width the same when altering column widths

I have an ng-grid with 6 columns in it, and as a default set up each column is 100px, so the grid itself is 600px. The columns are resizable but I want to keep the overall grid width the same, to ensure that there are no horizontal scroll bars. So, for example, if I change the second columns width to 150px I would want the overall width to stay at 600px (so maybe an adjacent cell will change size to 50px) - this way I don't get a scroll bar.
Does anybody know if there is a plugin that can do this/help me accomplish this?
I've included a plunker: http://plnkr.co/edit/4LRHQPg7w2eDMBafvy6b?p=preview
In this example, I would want to keep the table width at 600px, so if I expand "Field 2" you will see "Field 4" go off the edge of the viewable area for the grid and a horizontal scroll bar appear. The behaviour I want is for a different column (probably the adjacent column - "Field 3") to shrink in size automatically, so that the grid stays at 600px and the horizontal scroll bar doesn't appear.
After a lot of time searching the web for an answer, I started with Paul Witherspoon idea of watching the isColumnResizing property and after reading about ng-grid plugins I came up with this plugin solution:
Plunker: http://plnkr.co/edit/Aoyt73oYydIB3JmnYi9O?p=preview
Plugin code:
function anchorLastColumn () {
var self = this;
self.grid = null;
self.scope = null;
self.services = null;
self.init = function (scope, grid, services) {
self.grid = grid;
self.scope = scope;
self.services = services;
self.scope.$watch('isColumnResizing', function (newValue, oldValue) {
if (newValue === false && oldValue === true) { //on stop resizing
var gridWidth = self.grid.rootDim.outerWidth;
var viewportH = self.scope.viewportDimHeight();
var maxHeight = self.grid.maxCanvasHt;
if(maxHeight > viewportH) { // remove vertical scrollbar width
gridWidth -= self.services.DomUtilityService.ScrollW;
}
var cols = self.scope.columns;
var col = null, i = cols.length;
while(col == null && i-- > 0) {
if(cols[i].visible) {
col = cols[i]; // last column VISIBLE
}
}
var sum = 0;
for(var i = 0; i < cols.length - 1; i++) {
if(cols[i].visible) {
sum += cols[i].width;
}
}
if(sum + col.minWidth <= gridWidth) {
col.width = gridWidth - sum; // the last gets the remaining
}
}
});
}
}
and in the controller
$scope.gridOptions = {
data: 'myData',
enableColumnResize: true,
plugins: [new anchorLastColumn()],
columnDefs: $scope.columnDefs
};
It is not a perfect solution but works for me and I hope that it will help others.
I found a way to do this using a watch on the isColumnResizing property:
$scope.$watch('gridOptions.$gridScope.isColumnResizing', function (newValue, oldValue) {
if (newValue === false && oldValue === true) { //on stop resizing
$scope.ColResizeHandler($scope.gridOptions.$gridScope.columns);
}
}, true);
then I was able to resize the columns in the resize handler I created:
$scope.ColResizeHandler = function (columns) {
var origWidth;
var col1 = undefined;
var col2 = undefined;
var widthcol2;
var found = false;
var widthDiff = 0;
angular.forEach(columns, function (value) {
if (col2 == undefined && value.visible) {
if (found) {
origWidth += value.width;
col2 = value;
colSizeLimits(col2, widthDiff);
found = false;
}
if (value.origWidth != undefined && value.origWidth != value.width && col2 == undefined) {
found = true;
col1 = value;
widthDiff = value.width - value.origWidth;
origWidth = value.origWidth;
}
}
});
if (col2 == undefined) {
//this was the last visible column - don't allow resizing
col1.width = origWidth;
}
else {
//ensure limits haven't been blown to cope with reizing
if (col1.width + col2.width != origWidth) {
var diff = (col1.width + col2.width) - origWidth;
colSizeLimits(col1, diff);
}
}
col1.origWidth = col1.width;
col2.origWidth = col2.width;
}
There are 2 issues with this.
1 - if you resize and drag the column sizer outside of the grid (i.e. all the way over and out of the ng-grid viewable area) the isColumnResizing watch doesn't execute when you stop dragging and release the resizer. (I think this may be a bug in ng-grid because it does actually resize the column to where you have dragged the resizer, even if it is outside the grids viewable area, it just doesn't fire the watch code).
2 - if you avoid this issue and just drag within the viewable grid area then the columns will resize but only after you finish dragging the resizer, so the ui looks a little funny (i.e. if I expand a column then the adjacent column will not shrink until I click off the resizer and stop dragging).
I'll be working on these issues and will post any updates/fixes I find.

get column index of hide column in extjs grid panel

I need to get column index of hide column in extjs grid panel
columnhide: function() {
var cell = this.getEl().query('.x-grid-cell-inner');
for(var i = 0; i < cell.length; i++) {
if (i%2 != 0){ // Instead of this i, want to change the style to none for the hide column, so i need to get the column index of hide column in grid panel
cell[i].style.display= "none";
}
}
Using the columnhide listener:
columnhide: function(ct, column, eOpts) {
alert(column.getIndex());
},
Alternatively, you could loop through the grid columns and check the isHidden() property on each column:
Ext.each(grid.columns, function(column, index) {
if (column.isHidden()) {
alert('column at index ' + index + ' is hidden');
}
});
I have a test case set up here: http://jsfiddle.net/cCEh2/

Resources