我想使用ui-grid行选择功能来设置单击行中列的值。
我在名为omit
的数据库中有一列。我希望该值等于所选行的状态,因此如果选择了行,则omit
= 1,如果未选择行,则omit
= 0.我想我有这个部分的数字out(但我总是乐于接受更好的想法!)。
gridApi.selection.on.rowSelectionChanged($scope,function(row){
if(row.isSelected){
row.entity.omit = 1;
}
if(!row.isSelected){
row.entity.omit = 0;
}
// now save to database...
});
gridApi.selection.on.rowSelectionChangedBatch($scope,function(rows){
angular.forEach(rows, function(value, key) {
if(value.isSelected){
value.entity.omit = 1;
}
if(!value.isSelected){
value.entity.omit = 0;
}
// now save to database...
});
});
我无法弄清楚首次加载网格时如何选择行。
因此,在网格的初始加载时,如果omit
的值为1,如何选择行?
答案 0 :(得分:1)
您可以使用gridApi.selection.selectRow
方法,但必须等到网格消化数据才能生效。因此,您必须在$interval
(或$timeout
之后)将其设置为在网格摘要数据时继续运行,或者在致电{{1}之前调用gridApi.grid.modifyRows($scope.gridOptions.data)
说实话,我不确定你为什么要这么说。
selectRow
var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection']);
app.controller('gridCtrl', ['$scope', '$http', '$interval', 'uiGridConstants', function ($scope, $http, $interval, uiGridConstants) {
$scope.gridOptions = { enableRowSelection: true, enableRowHeaderSelection: false };
$scope.gridOptions.columnDefs = [
{ name: 'omit' },
{ name: 'id' },
{ name: 'name'},
{ name: 'age', displayName: 'Age (not focusable)', allowCellFocus : false },
{ name: 'address.city' }
];
$scope.gridOptions.multiSelect = false;
$scope.gridOptions.modifierKeysToMultiSelect = false;
$scope.gridOptions.noUnselect = true;
$scope.gridOptions.onRegisterApi = function( gridApi ) {
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope,function(row){
if(row.isSelected){
row.entity.omit = 1;
}
if(!row.isSelected){
row.entity.omit = 0;
}
// now save to database...
});
gridApi.selection.on.rowSelectionChangedBatch($scope,function(rows){
angular.forEach(rows, function(value, key) {
if(value.isSelected){
value.entity.omit = 1;
}
if(!value.isSelected){
value.entity.omit = 0;
}
// now save to database...
});
});
};
$scope.toggleRowSelection = function() {
$scope.gridApi.selection.clearSelectedRows();
$scope.gridOptions.enableRowSelection = !$scope.gridOptions.enableRowSelection;
$scope.gridApi.core.notifyDataChange( uiGridConstants.dataChange.OPTIONS);
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
_.forEach(data, function(row) {
row.omit = 0;
});
/* arbitrarily setting the fourth row's omit value to 1*/
data[3].omit = 1;
$scope.gridOptions.data = data;
/* using lodash find method to grab the row with omit === 1 */
/* could also use native JS filter, which returns array rather than object */
var initSelected = _.find($scope.gridOptions.data, function(row) { return row.omit === 1; });
$scope.gridApi.grid.modifyRows($scope.gridOptions.data);
$scope.gridApi.selection.selectRow(initSelected);
/**
* OR:
* $interval( function() {
* $scope.gridApi.selection.selectRow(initSelected);
* }, 0, 1);
*/
});
}]);