Jim Norman
Jim Norman

Reputation: 1

Cannot detect row selection in ui.grid

I have an angular ui grid working with selection, I want to populate a form with the contents of the selected record. I see no way to either reference the selected record or detect that row selection has occurred. Any ideas?

Upvotes: 0

Views: 1699

Answers (2)

PaulL
PaulL

Reputation: 6650

With ui-grid the api is a little different than the ng-grid example Aidan posted.

Normally you'd listen to the rowSelectionChanged event, refer: http://ui-grid.info/docs/#/api/ui.grid.selection.api:PublicApi

This would look something like the following:

$scope.selectionChanged = function( rowChanged ) {
  if( rowChanged.isSelected ){
    $scope.targetRow = rowChanged;
  }
};

gridOptions = {
  // other stuff
  onRegisterApi: function(gridApi) {
    $scope.gridApi = gridApi;
    $scope.gridApi.selection.on.rowSelectionChanged($scope, $scope.selectionChanged);
  } 
};

You should then be able to use $scope.targetRow as the target for your form. You'll probably need to turn off multiselect (check the selection gridOptions, or the selection tutorial), and deal with what happens when no row is selected.

In my application I tend to do the form as a popup (a modal or a separate page). When I do that it's much simpler, I just do a click event on the row itself, or (more commonly) a button on the row. Refer perhaps to http://ui-grid.info/docs/#/tutorial/305_appScope for an example. You can pass the row that was clicked upon into that click handler:

cellTemplate:'<button ng-click="grid.appScope.openModal( row.entity )">Edit</button>' }

You can then pass the entity (which would be an ngResource) into that modal, and once it edits it then it can just call save on the resource when it's done.

I did something similar to this in my (ng-grid based) tutorial series: https://technpol.wordpress.com/2013/11/09/angularjs-and-rails-4-crud-application-using-ng-boilerplate-and-twitter-bootstrap-3-tutorial-index/

Upvotes: 3

Aidan
Aidan

Reputation: 1750

It is customary to post what you have tried, please consider this in future. Here is a short sample that utilises the afterSelectionChange event for the ng-grid:

A grid with two divs to hold the selected data:

<div class='gridStyle' ng-grid='testGridOptions'></div>
<div>{{current.name}}</div>
<div>{{current.age}}</div>

some test data:

$scope.testData = [{name:'John', age:25}, 
                   {name:'Mary', age:30}, 
                   {name:'Fred', age:10}, 
                   {name:'Joan', age:20}];

configuration for the grid:

$scope.testGridOptions = {
                    data: 'testData', 
                    multiSelect: false,
                    afterSelectionChange: function(data){
                        $scope.current = data.entity;
                    }
};

Hope this gets you started.

Aidan

Upvotes: 0

Related Questions