how to set always selected first row ui-grid - angularjs

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

Related

How to set all the rows of ng-repeat to be selected in Angular

I have a smimple ng-repeat that displays user details. I am trying to set all the rows to be selected.
Currently I can manually click and select all the rows individually using following code:
<tr ng-repeat="room in classrooms" ng-class="{'selected': room.selected}" ng-click="select(room)">
in controller
$scope.select = function(item) {
item.selected ? item.selected = false : item.selected = true;
}
and to get data from the selected rows I use following logic
$scope.getAllSelectedRows = function()
{
var x = $filter("filter")($scope.classrooms,
{
selected: true
}, true);
console.log(x);
}
UPDATED FROM #KADIMA RESPONSE
$scope.toggleSelectAll = function()
{
angular.forEach($scope.classrooms, function(room) {
room.selected ? room.selected = false : room.selected = true;
})
}
Set up a new function in your controller:
$scope.selectAll = function() {
angular.forEach(classrooms, function(room) {
room.selected = true
}
}
And then you can create a button in your html to call this function.
If you want to select all data you got you can set selected property using angular.forEach() method.
https://docs.angularjs.org/api/ng/function/angular.forEach
In your case:
angular.forEach(x, fuction(value) {
value.selected = true;
}

Multiple dropdown selection in ag-grid (link Attached)

I need to have a column in ag-grid where i can select multiple values from dropdown. I just googled online to see if it is already implemented but i could find only one link.
https://gist.github.com/gaborsomogyi/00f46f3c0ee989b73c92
Can someone let me know how to implement it. show the full code as an example please.
Here is the code shared over there.
function agDropDownEditor(params, optionsName, optionsList) {
_.set(params.$scope, optionsName+'.optionsList', optionsList);
var html = '<span style="width:100%; display:inline-block" ng-show="!'+optionsName+'.editing" ng-click="'+optionsName+'.startEditing()">{{data.'+params.colDef.field+'}}</span> ' +
'<select style="width:100%" ng-blur="'+optionsName+'.editing=false" ng-change="'+optionsName+'.editing=false" ng-show="'+optionsName+'.editing" ng-options="item for item in '+optionsName+'.optionsList" ng-model="data.'+params.colDef.field+'">';
// we could return the html as a string, however we want to add a 'onfocus' listener, which is not possible in AngularJS
var domElement = document.createElement("span");
domElement.innerHTML = html;
_.set(params.$scope, optionsName+'.startEditing', function() {
_.set(params.$scope, optionsName+'.editing', true); // set to true, to show dropdown
// put this into $timeout, so it happens AFTER the digest cycle,
// otherwise the item we are trying to focus is not visible
$timeout(function () {
var select = domElement.querySelector('select');
select.focus();
}, 0);
});
return domElement;
}
Hope this helps, this is just a snippet of my code what i'm doing is I'm fetching from an array using map and then creating my object which is col and returning it and this will repeat till the last index of that array.
var col = {};
col.field = "fieldName";
col.headerName = "colName";
col.headerCellTemplate = function() {
var eCell = document.createElement('span');
eCell.field = obj.expr;
eCell.headerName = obj.colName;
eCell.innerHTML = "<select>"+"<option>"+
'Abc'+"</option>" +"<option>"+
'Xyz'+"</option>" +"</select>"
//$scope.dropDownTemplate;
var eselect = eCell.querySelector('select');
eselect.focus();
return eCell;
};
return col ;
}));

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;

AngularJS/Bootstrap - DataTables - Turn off certain dropdown filters in footer

Is it possible to turn off certain dropdown filters in the footer? This is the API I'm using: https://datatables.net/examples/api/multi_filter_select.html
I don't want all columns to be filterable. Also, is it possible to have the header labels be the default in the dropdown instead of a blank?
Here is my live example: http://live.datatables.net/cufawibi/3/
A usual approach is to use a css class to filter which columns can be filterable.
You could also add the column name as selected and disabled in order to display it as the default (included an all values options to disable the filter).
initComplete: function () {
var api = this.api();
api.columns('.filtersearch').indexes().flatten().each( function ( i ) {
var column = api.column( i );
var select = $('<select></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
select.append('<option selected disabled>"'+$(column.header()).text()+'"</option>');
select.append('<option value="">All values</option>');
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
} );
}
UPDATE:
In order to have the class added from the controller, changed also the table head definition to
<th ng-repeat="(i, th) in head" value="{{th.id}}" class="{{th.class}}"><span>{{th.name}}</span></th>
Live example (filter only for the "Payload" column, add filtersearch class to other columns to enable filtering)
I don't think there's a clean way to do this via the API. So this solution will be hacky.
So you'd wrap your logic around an IF block to filter out the columns dropdown filters you don't want to display.
api.columns().indexes().flatten().each(function (index) {
var column, select;
// You don't want to display the first and the fourth dropdown filter
if (index !== 0 || index !== 3) {
column = api.column(i);
select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
}
});

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

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

Resources